首页 文章

创建在现有ggplot2上绘制附加线和图例项的效果

提问于
浏览
0

我正在做一个演示文稿,并希望使用适当的图例呈现一个折线图(geom_line()) . 然后我想覆盖一个新的geom_line并添加相应的图例项 . 出于美观原因,我希望叠加层不会修改第一个图中给出的图例位置 . 效果应该是绘制现有图形并添加到其图例 .

如果我只是使用ggplot首先制作第一个绘图,然后使用两条线创建一个新绘图,则图例的位置会发生显着变化 .

如果我尝试将第一个绘图设置为完整绘图,但将其中一个行大小设置为零,则会遇到无法抑制大小为零的行的图例项的问题 .

如何用ggplot2实现我想要的效果?

编辑:

这是我第一次尝试的两个图形的代码 .

require(ggplot2)
require(reshape2)

x<-seq(-10,10,length=200)
G <- (1/(sqrt(2*pi))) * exp(-((x)^2)/(2))
G2 <- 2*(1/(pi))*(1/(x^2+1))

df = data.frame(x,G,G2)

ggplot(data = melt(data.frame(x,G),id.vars = 'x'))+
  geom_line(aes(x=x, y=value, color=variable),size=.5)+
  scale_color_manual("Distribution",values=c("orange"),labels=c("Gaussian"))+
  coord_cartesian(ylim = c(0, 1)) 

ggplot(data = melt(data.frame(x,G,G2),id.vars = 'x'))+
  geom_line(aes(x=x, y=value, color=variable),size=.5)+
  scale_color_manual("Distribution",values=c("orange","blue"),labels=c("Gaussian","2Gaussian"))+
  coord_cartesian(ylim = c(0, 1))

enter image description here

enter image description here

如果从这些图片中不清楚是否存在问题,请打开这两个链接中的图像并从一个链接翻转到另一个链接 .

http://rpubs.com/jwg/269311

http://rpubs.com/jwg/269312

NOTICE: The problem is even worse than I first described, since not only is the legend moving but the coordinate axis is moving as well.

据推测,这可以通过绘制两个然后使其图例项和线不可见来修复 . 这有可能吗?

2 回答

  • 2

    不确定这是不是你想要的,但是这里有:

    x<-seq(-10,10,length=200)
    G <- (1/(sqrt(2*pi))) * exp(-((x)^2)/(2))
    G2 <- 2*(1/(pi))*(1/(x^2+1))
    
    df <- data.frame(x,G,G2)
    df.plot <- tidyr::gather(df, key = 'variable', value = 'value', -x)
    
        ggplot(df.plot, aes(x, value, color = variable)) + geom_line() + scale_color_manual(breaks = c("G"), values = c("orange", NA)) + 
    coord_cartesian(xlim = c(-10, 10), ylim = c(0,1)) + theme(legend.position = c(0,0)) + 
    theme(legend.position = "right",
    legend.justification = "top")
    
    ggplot(df.plot, aes(x, value, color = variable)) + geom_line() + scale_color_manual(breaks = c("G", "G2"), values = c("orange", "blue")) + 
    coord_cartesian(xlim = c(-10, 10), ylim = c(0,1)) + theme(legend.position = "right",
    legend.justification = "top")
    
  • 1

    这是一个解决方案,它将使所有内容与动画奖励保持一致 .

    library(ggplot2)
    library(tidyr)
    library(gganimate)
    
    p <- df %>% 
      gather(var, val, -x) %>% 
      ggplot(aes(x, val, frame = var)) + 
        geom_line(aes(color = var, group = var, cumulative = TRUE)) +
        coord_cartesian(ylim = c(0, 1))
    
    gganimate(p, "myplot.gif", "gif")
    

    这应生成一个文件 myplot.gif ,结果如下:
    enter image description here

相关问题