【问题标题】:problem with legend while plotting data from two data.frame绘制来自两个data.frame的数据时的图例问题
【发布时间】:2010-12-19 17:50:56
【问题描述】:

我在让 ggplot2 按我的意愿工作时遇到了一点麻烦。基本上,我想通过将它们放在一个图中来比较实际观察结果与近似值。例如,

> library(ggplot2)
> df.actual <- data.frame(x = 1:100, y = (1:100) * 2)
> df.approx <- data.frame(x = 1:150, y = (1:150) * 2 + 5  + rnorm(150, mean = 3) )
> ggplot() + geom_point(aes(x, y), data = df.actual) + geom_line(aes(x,y), data = df.approx)

我的问题是我无法显示图例。我在某处读到 ggplot2 的图例不是很灵活(?)。理想情况下,一个带有

的图例
  • title = '类型'
  • 键:黑色实心点和黑色线条
  • 关键标签:“实际”、“近似”
  • legend.position = 'topright'

谢谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试这个让你开始

    ggplot() + 
      geom_point(aes(x, y, colour = "actual"), data = df.actual) + 
      geom_line(aes(x, y, colour = "approximate"), data = df.approx) + 
      scale_colour_discrete("Type")
    

    【讨论】:

    • 谢谢哈德利,我想区分日期黑白情节。有没有可能像我描述的那样有一个图例,它的两个键是点和线?
    【解决方案2】:

    这是一种通过操纵网格对象来修改图例的技巧:

    library("ggplot2")
    df.actual <- data.frame(x=1:100, y=(1:100)*2)
    df.approx <- data.frame(x=1:150, y=(1:150)*2 + 5 + rnorm(150, mean=3))
    p <- ggplot() +
         geom_point(aes(x, y, colour="Actual"), data=df.actual) +
         geom_line(aes(x, y, colour="Approximate"), data=df.approx) +
         scale_colour_manual(name="Type",
                             values=c("Actual"="black", "Approximate"="black"))
    library("grid")
    grob <- ggplotGrob(p)
    tmp <- grid.ls(getGrob(grob, "key.segments", grep=TRUE, global=TRUE))$name
    grob <- removeGrob(grob, tmp[1])  # remove first line segment in legend key
    tmp <- grid.ls(getGrob(grob, "key.points", grep=TRUE, global=TRUE))$name
    grob <- removeGrob(grob, tmp[2])  # remove second point in legend key
    grid.draw(grob)
    

    ggplot2 output http://img134.imageshack.us/img134/8427/ggplotlegend.png

    【讨论】:

    • 感谢您提供可重现的示例。 ggplot2 应该会自动处理这种类型的图例,所以我会将其添加到我的待办事项列表中。
    • 这不再起作用了:In removeGrob(grob, tmp[1]) : 'gPath' (layout) not found。我想一些内部安排和/或命名已经改变了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    相关资源
    最近更新 更多