我尝试在ggplot2绘图中添加图例,但无法正常工作。此外,命令show.legend不会更改任何内容

在回答了这个问题(Adding manual legend in ggplot)之后,我尝试了scal_colour_manueal,但没有成功

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, group = kpi) ) +
  geom_line(color=color1, show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, group = kpi), colour = color2 , show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)


如何在图中添加图例?

最佳答案

如果希望它们取决于数据框的某些变量,则不应在aes之外设置颜色。

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, col= kpi) ) +
  geom_line(show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, col= kpi), show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)

r - 向ggplot2添加图例-LMLPHP

关于r - 向ggplot2添加图例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56337690/

10-11 08:15