【问题标题】:overlaying plots from different dataframes in ggplot without messing with legend在ggplot中覆盖来自不同数据框的图而不弄乱图例
【发布时间】:2019-02-15 16:05:17
【问题描述】:

我想叠加两个图:一个是简单的点图,其中一个变量用于控制点的大小;另一个是简单的曲线。

这是第一个情节的虚拟示例;

library(ggplot2)
x <- seq(from = 1, to = 10, by = 1)
df = data.frame(x=x, y=x^2, v=2*x)
ggplot(df, aes(x, y, size = v)) + geom_point() + theme_classic() + scale_size("blabla")

现在让我们用来自另一个数据框的数据覆盖一条曲线到该图:

df2 = data.frame(x=x, y=x^2-x+2)
ggplot(df, aes(x, y, size = v)) + geom_point() + theme_classic() + scale_size("blabla") + geom_line(data=df2, aes(x, y), color = "blue") + scale_color_discrete(name = "other", labels = c("nanana"))

它会产生错误:

FUN(X[[i]], ...) 中的错误:找不到对象“v”

v 中的值不是用来绘制预期的诅咒的,但无论如何,我在 df2 中添加了一个虚拟 v。

df2 = data.frame(x=x, y=x^2-x+2, v=replicate(length(x),0))  # add a dummy v
ggplot(df, aes(x, y, size = v)) + geom_point() + theme_classic() + scale_size("blabla") + geom_line(data=df2, aes(x, y), color = "blue") + scale_color_discrete(name = "other", labels = c("nanana"))

一个结果有一个乱七八糟的传说:

实现理想情节的正确方法是什么?

【问题讨论】:

    标签: r dataframe ggplot2 legend


    【解决方案1】:

    您可以将大小 aes 放在 geom_point() 调用中以使其不需要df2 中的虚拟 v。

    不确定您想要关于图例的确切内容。如果你替换上面的,那么蓝色部分就会消失。如果您想为线条颜色添加图例,则必须在 geom_line aes 调用中放置颜色。

    x <- seq(from = 1, to = 10, by = 1)
    df = data.frame(x=x, y=x^2, v=2*x)
    df2 = data.frame(x=x, y=x^2-x+2)
    
    ggplot(df, aes(x, y)) + 
      geom_point(aes(size = v)) + 
      theme_classic() + 
      scale_size("blabla") + 
      geom_line(data=df2, aes(x, y, color = "blue")) +
      scale_color_manual(values = "blue", labels = "nanana", name = "other")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多