ggplot does not show legend in geom_histogram

后端 未结 2 2042
梦毁少年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

    0 讨论(0)
  • 2020-12-11 21:52

    If you don't want to put the data in one data.frame, you can do this:

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

    enter image description here

    0 讨论(0)
提交回复
热议问题