创建在现有ggplot2

时间:2017-04-20 00:02:32

标签: r ggplot2

我正在制作演示文稿,并希望使用适当的图例呈现一个折线图(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

注意:问题甚至比我先描述的还要糟糕,因为不仅是图例在移动,而且坐标轴也在移动。

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

2 个答案:

答案 0 :(得分:2)

这是一个解决方案,可以使所有内容与动画奖励保持一致。

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

答案 1 :(得分:1)

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

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