problem with legend while plotting data from two data.frame

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

I'm having a little trouble with getting ggplot2 to work as I want. Basically, I'd like to compare actual observations vs. approximated by putting them in one single plot. For example,

> 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) 

My problem is that I can't display a legend. I read somewhere that ggplot2's legend is not very flexible(?). Ideally, a legend with

  • title = 'Type'
  • key: a black filled point, and a black line
  • key label: 'Actual', 'Approximate'
  • legend.position = 'topright'

Thanks.

回答1:

Try this to get you started

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:

This is some kind of hack to modify the legend by manipulation of the grid object:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!