I want to create a chart where I plot an entry (e.g. a geom_point) for EACH of a quantity value within a data frame.
Below, I have created a simplified version of the original data frame that I imagine I need in a resulting dataframe from which I can do the plot, as I believe ggplot will need a separate row for each.
In the example, I'd like to plot 3 Red points at position x, with y calculated based on a sequential count for each entry in the original data frame (in the example, this is 1-3 for Red and 1-4 for Blue).
I think this is probably possible using Apply and a custom function, but I'm a bit lost on how to proceed.
library(tidyverse)
origInput <- data.frame(x = c(7,2), colour = c("Red", "Blue"), quantities = c(3, 4))
desiredOutput <- data.frame(x = c(7,7,7,2,2,2,2),
colour = c("Red", "Red", "Red", "Blue", "Blue", "Blue", "Blue"),
y = c(1, 2, 3, 1, 2, 3, 4))
ggplot(desiredOutput, aes(x = x, y = y, colour = colour))
geom_point()
extrapolator <- function() {}
output <- apply(df, 2, extrapolator)
ggplot(output, ...)
CodePudding user response:
As mentioned in the comments, you can use ungroup() to duplicate the rows. To get the y values, first group by the color then set the y variable as the row number.
transformed <- origInput %>%
uncount(quantities) %>%
group_by(colour) %>%
mutate(y = row_number()) %>%
ungroup()
The final plot is:
CodePudding user response:
Thanks @aosmith.
This works perfectly.
output <- uncount(origInput, quantities, .id = "y")
ggplot(output, aes(x = x, y = y, colour = colour)) geom_point()

