【问题标题】:ggplot does not show legend in geom_histogramggplot 在 geom_histogram 中不显示图例
【发布时间】:2014-07-24 11:53:04
【问题描述】:

我有这个代码

ggplot()
+ geom_histogram(aes(x=V1, y=(..count..)/sum(..count..)), fill="red", alpha=.4, colour="red", data=coding, stat = "bin", binwidth = 30)
+ geom_histogram(aes(x=V1,y=(..count..)/sum(..count..)), fill="blue", alpha=.4, colour="blue", data=lncrna, stat = "bin", binwidth = 30)
+ coord_cartesian(xlim = c(0, 2000))
+ xlab("Size (nt)")
+ ylab("Percentage (%)")
+ geom_vline(data=cdf, aes(xintercept=rating.mean, colour=Labels), linetype="dashed", size=1)

生成没有图例的漂亮直方图:

在我遇到相同问题的每个帖子中,他们都说将color 放入aes。然而,这并没有给出任何传说。

我试过了:

ggplot() + geom_histogram(aes(x=V1, y=(..count..)/sum(..count..),color="red", fill="red"), fill="red", alpha=.4, colour="red", data=coding, stat = "bin", binwidth = 30)
+ geom_histogram(aes(x=V1,y=(..count..)/sum(..count..), color="blue", fill="blue"), fill="blue", alpha=.4, colour="blue", data=lncrna, stat = "bin", binwidth = 30)
+ coord_cartesian(xlim = c(0, 2000))
+ xlab("Size (nt)")
+ ylab("Percentage (%)")
+ geom_vline(data=cdf, aes(xintercept=rating.mean, colour=Labels), linetype="dashed", size=1)

没有成功。

如何在图表中添加图例?

【问题讨论】:

  • 您是否尝试在美学映射中指定填充/颜色?我在你的代码中没有看到。一些example data 可以更轻松地向您展示如何做到这一点。
  • 什么是美学映射?
  • @user2979409:这是你使用的aes()函数。
  • 如果在 aes 内指定,则不应在 aes 外指定。
  • 我会将codinglncrna 合并到一个对象中,并附加一列来说明数据来自(假设变量名为origin)。您将其映射到aes(),例如ggplot(merged.data, aes(..., fill = origin)) + geom_histogram()。您可以通过比例控制特定的颜色。见docs.ggplot2.org/current

标签: r ggplot2


【解决方案1】:

如果您不想将数据放在一个 data.frame 中,可以这样做:

set.seed(42)
coding <- data.frame(V1=rnorm(1000))
lncrna <- data.frame(V1=rlnorm(1000))


library(ggplot2)
ggplot() + 
  geom_histogram(aes(x=V1, y=(..count..)/sum(..count..), fill="r", colour="r"), alpha=.4, data=coding, stat = "bin") +
  geom_histogram(aes(x=V1,y=(..count..)/sum(..count..), fill="b", colour="b"), alpha=.4, data=lncrna, stat = "bin") +
  scale_colour_manual(name="group", values=c("r" = "red", "b"="blue"), labels=c("b"="blue values", "r"="red values")) +
  scale_fill_manual(name="group", values=c("r" = "red", "b"="blue"), labels=c("b"="blue values", "r"="red values"))

【讨论】:

  • 可以从输出中删除图例名称吗?
【解决方案2】:

问题是您无法将颜色映射到 aes,因为您有两组单独的数据。一个想法是绑定它们,然后应用 reshape2 包的“melt”函数,以便创建一个可以传递给 aes 的虚拟分类变量。代码:

require(reshape2)
df=cbind(blue=mtcars$mpg, red=mtcars$mpg*0.8)
df=melt(df, id.vars=1:2)
ggplot()+geom_histogram(aes(y=(..count..)/sum(..count..),x=value, fill=Var2, color=Var2), alpha=.4, data=df, stat = "bin")

你有你的传奇

【讨论】:

  • re:使用这个,您的条形图将被闪避或堆叠,但您可以调整位置参数以叠加条形图:“position=position_dodge(width=0)”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多