首页 > 解决方案 > 我可以在不使用 aes() 的情况下手动向 ggplot 添加图例吗?

问题描述

我用 stat_ecdf 函数做了一个 CDP 图,但我不能添加图例。这是 CDP 图的代码:

ggplot()+
      stat_ecdf(data=df, aes(Apple), geom = "step", col ="red")+
      stat_ecdf(data=df, aes(Ocean), geom = "step", col ="blue")+
      stat_ecdf(data=df, aes(Tree), geom = "step", col ="green")+
      stat_ecdf(data=df, aes(Citron), geom = "step", col ="yellow")+
      stat_ecdf(data=df, aes(Sun), geom = "step", col ="orange")+
      labs(y="Cumulative Probability",x="Proportion of samples (>1 FIB per 100 mL)",col="Legend")+
      theme_classic()

情节出现,但没有传说。我想有一个传说,描述红线=苹果,蓝线=海洋等。谢谢。

标签: rggplot2

解决方案


ggplot 可以更好地处理长格式的数据。您可以重塑数据,使 x 变量位于单个列中,并且有一列区分颜色,然后您可以在绘图中添加颜色列作为美学。您希望您的数据采用这种形式

df = bind_rows(
  # apple df
  data.frame(x=runif(100,-10,10),col_column='Apple',
             stringsAsFactors = F),
  # ocean df
  data.frame(x=runif(100,0,20),col_column='Ocean',
             stringsAsFactors = F),
  # tree df
  data.frame(x=rnorm(100,mean=0,sd=2),col_column='Tree',
             stringsAsFactors = F)
)

head(df)

# x col_column
# 1 -3.3221018      Apple
# 2 -9.8157569      Apple
# 3  9.7496057      Apple
# 4 -8.4488035      Apple
# 5 -8.4584002      Apple
# 6  0.9613705      Apple

我实际上看不到您的数据,但根据您使用它的方式,我假设它只有 columns AppleOceanTree等。如果是这样,您可以使用 dplyr 的 gather 函数以长格式重塑。

df = dplyr::gather(df,key='col_column',value='x')

然后你可以像这样重新安排你的 ggplot 调用。

ggplot(data=df,mapping=aes(x,color=col_column)) +
  stat_ecdf(geom='step') +
  scale_color_manual(values=c('Apple'='red','Ocean'='blue','Tree'='green'))

示例图形

这可以防止你重写stat_ecdf你想要的每一列/颜色。


推荐阅读