Проблема с легендой при построении данных из двух данных.

StackOverflow https://stackoverflow.com/questions/1787578

  •  21-09-2019
  •  | 
  •  

Вопрос

У меня есть небольшие проблемы с тем, чтобы заставить 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 = 'type'
  • Ключ: черная точка и черная линия
  • Ключевая метка: «Фактическое», «Примерный»
  • Legend.position = 'Topright'

Спасибо.

Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top