【问题标题】:How to add inside legend for a combined plot in ggplot2如何在ggplot2中为组合图添加内部图例
【发布时间】:2017-09-25 06:37:04
【问题描述】:

我有以下 df 和 ggplot2 代码来制作散点图,但未能在图中添加图例。谢谢:)

x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6

df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x=x1, y = y1),col='red') + geom_point(aes(x = x2, y = y2),col='black')

【问题讨论】:

  • 将 col 参数放在 aes 定义中
  • 您可以使用scale_color_manual 更改标签名称
  • 感谢 Patrik_P,它起作用了,但是我不让我改变颜色

标签: r ggplot2


【解决方案1】:

试试:

x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6

df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x=x1, y = y1, col = "1")) + 
geom_point(aes(x = x2, y = y2, col = "2")) + scale_colour_manual(values = c("red", "black"))

在上面的代码中,通过将 col = "1" 和 col = "2" 放入 美学 aes(),您告诉 ggplot 为绘图添加颜色维度(并且不仅仅是给点“红色”和“黑色”上色)。因此,您现在看到了一个传奇。然后,通过将颜色设置为“1”和“2”,您就是说将它们用作标签。 scale_colour_manual 允许您将这些颜色更改为红色和黑色,而不是默认的红色和蓝色。

这同样适用于您想在绘图中添加任何维度的任何时候。但是,您可以使用shapescale_shape_manual 等替代方案,而不是使用colscale_colour_manual

【讨论】:

    【解决方案2】:

    这里是长格式数据输入的一种方式

    #data into long format
    x1 = 1:5 
    x2 = 6:10
    y1 = 3:7
    y2 = 2:6
    df <- data.frame(x=c(x1, x2), y=c(y1, y2), group=rep(c("x1", "x2"), c(5, 5)))
    #plot it
    library(ggplot2)
    ggplot(df) + 
      geom_point(aes(x=x, y = y, colour=group))+
      scale_colour_manual(values=c("red", "black"))
    

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      相关资源
      最近更新 更多