问题
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.
回答1:
The following code should give you the desired result:
# creating reproducible data
set.seed(1)
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, groups)
# creating the plot
ggplot(data=data_table, aes(x=factor(factors), y=data, color=groups)) +
geom_point() +
geom_errorbar(stat = "hline", yintercept = "mean", width=0.6, aes(ymax=..y.., ymin=..y.., group=factor(factors)), color="black")
which gives:
Checking whether the means are correct:
> by(data_table$data, data_table$factors, mean)
data_table$factors: 1
[1] 15.12186
-------------------------------------------------------------------------------------------------
data_table$factors: 2
[1] 15.03746
-------------------------------------------------------------------------------------------------
data_table$factors: 3
[1] 15.24869
which leads to the conclusion that the means are correctly displayed in the plot.
Following the suggestion of @rrs, you could also combine it with a boxplot:
ggplot(data=data_table, aes(x=factor(factors), y=data, color=groups)) +
geom_boxplot(aes(middle=mean(data), color=NULL)) +
geom_point(size=2.5)
which gives:
However, the middle line represents the median and not the mean.
来源:https://stackoverflow.com/questions/24487007/add-average-lines-for-categorical-scatterplots-with-single-group-values