传说ggplot2和geom_point

时间:2015-05-04 22:45:51

标签: r ggplot2

我正在尝试使用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

我想要一个传奇,告诉他们你的平均得分的圆圈。三角形是您学校的平均分数。广场是该地区的平均值。我找了办法做到这一点找不到办法。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:5)

ggplot喜欢整洁的数据,这意味着您必须将数据融合为长格式。

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

现在,您的数据只有一列我们会映射到shape,因此自动图例会起作用。 并且无需添加到同一个绘图并将其保存在每一行中,只需一次添加即可。 请不要在data$column内指定aes()!如果您想要刻面或进行更高级的绘图,它将导致问题。您可以预先指定数据,因此您不必在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  ")) +