I've searched the posts but can't find a specific example that helps me solve my problem. (This is my first post so I can't include images directly, but I included a link and the code should work to illustrate my problem.)
I am trying to make a grouped graph in ggplot where I have a bar plot showing the mean and then individual points showing the individual replicates. I can get it to work properly if I don't change the shape of the points according to a specific group.
However, I would like to shape the points by the replicate. When I try to do that, geom_point seems to group things incorrectly and the points no longer correspond to the data shown in the bar graph.
Here is some example data. There are 4 sources of fruit, 4 different types of fruit, and 2 replicates for each source/fruit combination.
values <- runif(n = 32, min = 50, max = 100)
source <- rep(c("grocery", "garden", "market", "farm"), each = 8)
replicate <- rep(c("A", "B"), times = 16)
fruit <- rep(c("apple", "orange", "banana", "grape"), each = 2, times = 4)
df <- data.frame(source, fruit, replicate, values)
# change fruit to factor
df$fruit <- factor(df$fruit, levels = c("apple", "orange", "banana", "grape"))
Now I make a bar graph, which graphs the mean of the two replicates and groups the four fruits together by the four sources.
g <- ggplot(data = df, aes(x = source, y = values, fill = fruit)) +
geom_bar(position = "dodge", color = "black", stat = "summary", fun = "mean") +
scale_fill_manual(values = c("gray65", "deepskyblue1", "orange", "olivedrab4")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
legend.position = "top",
legend.title = element_text(face = "bold", size = 10),
legend.text = element_text(size = 10),
strip.text = element_text(size = 10, face = "bold"),
legend.background = element_rect(size=.5, linetype="solid", color = "black"))
g
Next, I add in points to show the two replicates. This works fine.
#add in geom_point to show duplicates
g + geom_point(position = position_dodge(width = 0.9))
However, when I try to add different shapes for the two replicates, now it groups the replicates together instead of keeping on replicate for each point. So the points don't correspond correctly to the bar graphs. I tried adding "shape = replicate" to the aes in the first ggplot line, but that causes there to be individual bar graphs for each replicate. I am sure I'm close, but can't figure out what else to try.
#make the shape of the points correspond to the celltype
g + geom_point(aes(shape = replicate), position = position_dodge(width = 0.9))