ggplot does not show legend in geom_histogram

后端 未结 2 2046
梦毁少年i
梦毁少年i 2020-12-11 21:41

I have this code

ggplot()
+ geom_histogram(aes(x=V1, y=(..count..)/sum(..count..)), fill=\"red\", alpha=.4, colour=\"red\", data=coding, stat = \"bin\", binw         


        
2条回答
  •  眼角桃花
    2020-12-11 21:44

    The problem is that you can't map your color into aes because you've got two separete sets of data. An idea is to bind them, then to apply the "melt" function of package reshape2 so you create a dummy categorical variable that you can pass into aes. the code:

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

    There you've got your legend

提交回复
热议问题