I have a categorical scatter plot like this:
which I generated in R with the following code (using the ggplot2 library):
data <- runif(50, 13, 17)
factors <- as.factor(sample(1:3, 50, replace = TRUE))
groups <- as.factor(sample(1:3, 50, replace = TRUE))
data_table <- data.frame(data, factors)
g <- ggplot(data_table, aes(y = data_table[, 1], x = data_table[, 2], colour = groups)) + geom_point(size = 1.5)
I am trying to add an average line for each x-group, but I can't manage to find the right way. I have already tried with the procedure described in this question, but it doesn't work, I reckon because my x-groups are composed of a single x-value each, for which I believe the procedure should be different.
More in detail, if I add:
+ geom_line(stat = "hline", yintercept = "mean", aes(colour = data_table[, 2]))
to the previous code line, it gives me the following error: geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?.
If I try with the procedure suggest in the answer to that question, by adding:
+ geom_errorbar(stat = "hline", yintercept = "mean", width=0.8, aes(ymax=..y..,ymin=..y..))
to my initial code (I have removed the geom_jitter(position = position_jitter(width = 0.4))
piece of code, because it added random points to my data plot), I get three lines for each group (each corresponding to the mean of the three groups indicated in red, green, blue for that specifical x-group), as shown in this picture:
Does anyone have any suggestion on how to fix this?
Thank you.