繁体   English   中英

带有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()再说一次。 并对所有美学映射使用aes() ,例如误差栏的最小值和最大值。

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

如果需要更好的标签,可以在形状比例中指定它们。 在水平图例中,我喜欢添加一些空白,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM