ggplot2图例不出现的原因

MBo*_*org 8 r legend ggplot2

我试图(不成功)在我的 R ggplot2 图中显示一个图例,它涉及多个图。我的数据框df和代码如下:

  Individuals        Mod.2        Mod.1          Mod.3
1           2 -0.013473145  0.010859793    -0.08914021
2           3 -0.011109863  0.009503278    -0.09049672
3           4 -0.006465788  0.011304668    -0.08869533
4           5  0.010536718  0.009110458    -0.09088954
5           6  0.015501212  0.005929766    -0.09407023
6           7  0.014565584  0.005530390    -0.09446961
7           8 -0.009712516  0.012234843    -0.08776516
8           9 -0.011282278  0.006569570    -0.09343043
9          10 -0.011330579  0.003505439    -0.09649456

str(df)
    'data.frame':   9 obs. of  4 variables:
     $ Individuals   : num  2 3 4 5 6 7 8 9 10
     $ Mod.2         : num  -0.01347 -0.01111 -0.00647 0.01054 0.0155 ...
     $ Mod.1         : num  0.01086 0.0095 0.0113 0.00911 0.00593 ...
     $ Mod.3         : num  -0.0891 -0.0905 -0.0887 -0.0909 -0.0941 ...

ggplot(df, aes(df$Individuals)) +
    geom_point(aes(y=df[,2]), colour="red") + geom_line(aes(y=df[,2]), colour="red") +
    geom_point(aes(y=df[,3]), colour="lightgreen") + geom_line(aes(y=df[,3]), colour="lightgreen") +
    geom_point(aes(y=df[,4]), colour="darkgreen") + geom_line(aes(y=df[,4]), colour="darkgreen") +
    labs(title = "Modules", x = "Number of individuals", y = "Mode")
Run Code Online (Sandbox Code Playgroud)

我查找了以下堆栈流线程以及 Google 搜索:

这让我意识到让图例出现是一个反复出现的问题,尽管图例通常会自动出现。

我的第一个问题是使用 ggplot 时不出现图例的原因是什么?二是如何解决这些原因。原因之一似乎与多个地块和 的使用有关aes(),但我怀疑还有其他原因。

小智 20

colour= XYZ应该在里面aes(),而不是外面:

geom_point(aes(data, colour=XYZ)) #------>legend

geom_point(aes(data),colour=XYZ)  #------>no legend
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助,我花了很长时间才弄清楚。

  • 在这种情况下,颜色声明不起作用。\ 我目前有类似的问题(这就是我在这里的原因:))。我有一个包含多个 geom_line() 命令的图,我希望这些线具有热图颜色,但它们是彩虹色的。\ 当我将 color="black" 放入 aes() 中时,颜色不处于活动状态并且没有黑线。\ 当我将颜色从 aes() 中取出时,其中一根线变成黑色;颜色处于活动状态,但该行的图例消失。\ 我还无法同时成功实现图例和颜色。 (3认同)

ala*_*han 9

您正在以完全错误的方式进行颜色设置。您已在多个图层中将颜色设置为常量字符值,而不是将其映射到单个图层中的变量值。

这主要是因为您的数据不“整洁”(见下文

head(df)
  x           a          b          c
1 1 -0.71149883  2.0886033  0.3468103
2 2 -0.71122304 -2.0777620 -1.0694651
3 3 -0.27155800  0.7772972  0.6080115
4 4 -0.82038851 -1.9212633 -0.8742432
5 5 -0.71397683  1.5796136 -0.1019847
6 6 -0.02283531 -1.2957267 -0.7817367
Run Code Online (Sandbox Code Playgroud)

相反,您应该首先重塑您的数据:

df <- data.frame(x=1:10, a=rnorm(10), b=rnorm(10), c=rnorm(10))
mdf <- reshape2::melt(df, id.var = "x")
Run Code Online (Sandbox Code Playgroud)

这会产生更合适的格式:

head(mdf)
 x variable       value
1 1        a -0.71149883
2 2        a -0.71122304
3 3        a -0.27155800
4 4        a -0.82038851
5 5        a -0.71397683
6 6        a -0.02283531
Run Code Online (Sandbox Code Playgroud)

这将使以预期方式与 ggplot2 一起使用变得更加容易,其中颜色映射到变量的值:

ggplot(mdf, aes(x = x, y = value, colour = variable)) + 
    geom_point() + 
    geom_line()
Run Code Online (Sandbox Code Playgroud)

ggplot 调用的输出