ggplot不会在geom_histogram中显示图例

use*_*409 4 r ggplot2

我有这个代码

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)
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

在我访问的每个帖子中都遇到同样的问题,他们说放在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)
Run Code Online (Sandbox Code Playgroud)

没有成功.

如何在图表中添加图例?

Rol*_*and 8

如果您不想将数据放在一个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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


age*_*nis 5

问题是您无法将颜色映射到es,因为您有两个独立的数据集。一个想法是绑定它们,然后应用包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")
Run Code Online (Sandbox Code Playgroud)

那里有你的传奇