ggplot在geom_histogram中没有显示图例

4
我有这段代码。
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)

没有成功。

我如何在我的图表中放置图例?


1
你尝试在美学映射中指定填充/颜色了吗?我在你的代码中没有看到这个。一些示例数据会更容易向您展示如何做到这一点。 - Roland
@user2979409:你需要使用aes()函数。 - Steve S
是的,我尝试过了。我更新了我的帖子。 - user2979409
2
如果您在 aes 内指定了它们,则不应在其外部指定它们。 - Roland
1
我会将 codinglncrna 合并成一个对象,并加入另一列来指示数据来源(假设该变量名为 origin)。您可以在 aes() 中进行映射,例如 ggplot(merged.data, aes(..., fill = origin)) + geom_histogram()。您可以通过 scales 来控制具体的颜色。请参考 http://docs.ggplot2.org/current/。 - Roman Luštrik
显示剩余2条评论
2个回答

12

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

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"))

在此输入图片描述


可以从输出中删除图例名称吗? - simone

5

问题在于您不能将颜色映射到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")

这是您的图例


1
关于使用这个功能,你的条形图可以被分组或叠加,但你可以通过调整位置参数来使它们重叠:"position=position_dodge(width=0)"。 - agenis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接