ggplot2 和 geom_point 的图例

Legend with ggplot2 and geom_point

我试图在使用 ggplot2 和 geom_point 时创建图例。我有一个看起来像这样的数据框

d <- data.frame(variable = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"),
            value = rnorm(10, 3),
            Schoolave = rnorm(10, 3),
            districtave = rnorm(10, 3),
            max = rnorm(10, 3),
            min = rnorm(10, 3))

我想制作一个看起来像这样的情节。

plot <- ggplot(data = d, aes(x = variable, y = value)) + geom_errorbar(ymax = d$max, ymin = d$min) 

plot <- plot + coord_flip() 
plot <- plot + geom_point(data = d, aes(x = variable, y = value), 
                                                shape = 1, size = 5)
plot <- plot + geom_point(data = d, aes(x = variable, y = districtave), shape = 0, size = 4)
plot <- plot + geom_point(data = d, aes(x = variable, y = Schoolave), shape = 2, size = 3)
plot <- plot + theme_bw() + theme(legend.position= "bottom") 
plot

我想要一个图例,告诉他们你的平均分数是多少。三角形是您学校的平均分数。正方形是该地区的平均值。我一直在寻找一种方法来做到这一点找不到方法。任何帮助,将不胜感激。

ggplot喜欢整洁的数据,这意味着你必须把你的数据融化成长格式。

library(reshape2)
d.points = melt(d[, c("variable", "value", "Schoolave", "districtave")],
                id = "variable",
                variable.name = "type")

现在您的数据只有一个列,我们将其映射到 shape,因此自动图例将起作用。 并且无需添加到同一个绘图并保存每一行,只需一次添加即可。 并且请不要在 aes() 中指定 data$column!如果你想分面或做更高级的情节,它会引起问题。您预先指定数据,因此您不必在 aes() 中再次说出来。并且 doaes() 用于所有美学映射,例如误差条的最小值和最大值。

plot <- ggplot(data = d, aes(x = variable, y = value)) + 
    geom_errorbar(aes(ymax = max, ymin = min)) +
    coord_flip() +
    geom_point(data = d.points,
               aes(x = variable, y = value, shape = type),
               size = 5) +
    scale_shape_manual(values = 1:3, name = "") +
    theme_bw() + 
    theme(legend.position= "bottom") 
plot

如果你想要更好的标签,你可以在形状比例中指定它们。在水平图例上,我喜欢添加一点白色 space,像这样:

scale_shape_manual(values = 1:3, name = "",
                   labels = c("Individual Average  ", "School Average  ", "District Average  ")) +