Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

r - ggplot2: how to remove slash from geom_density legend

I'm trying to plot some overlapping density plots in ggplot2. I'm running into a problem where I cannot remove the diagonal slash from the legend. I have tried using scale_fill_manual() and legend.key as well as the hack from R Cookbook, but I cant seem to get it right.

data(iris)
iris=iris
cols=brewer.pal(3,"Set1")

ggplot(iris) + 
    geom_density(position="identity",aes(x=iris$Sepal.Length,fill=cols[1]),
        colour="black",alpha=.5) +
    geom_density(position="identity",aes(x=iris$Sepal.Width,fill=cols[2]),
        colour="black",alpha=.5)+  
    theme_bw() +
    scale_fill_identity(guide="legend",labels=c("Sepal Width","Sepal Length"))+
    xlab("X axis") +
    theme(panel.background=element_blank(),
        legend.title=element_blank(),
        legend.key = element_rect(),
        legend.background = element_blank(),
        legend.justification=c(1,0), 
        legend.position=c(.75,.5),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

enter image description here

What can I do to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

+ guides(fill = guide_legend(override.aes = list(colour = NULL)))

although that removes the black outline as well...which can be added back in by change the theme to:

legend.key = element_rect(colour = "black")

I completely forgot to add this important note: do not specify aesthetics via x=iris$Sepal.Length using the $ operator! That is not the intended way to use aes() and it will lead to errors and unexpected problems down the road.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...