ggplot2:如何从geom_density图例中删除斜杠 [英] ggplot2: how to remove slash from geom_density legend

查看:408
本文介绍了ggplot2:如何从geom_density图例中删除斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ggplot2中绘制一些重叠的密度图。我遇到了一个问题,我无法从图例中删除斜线斜线。我尝试过使用scale_fill_manual()和legend.key以及R Cookbook的黑客攻击,但我似乎无法做到。

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

我能做些什么来解决这个问题?

What can I do to solve this?

推荐答案

试试这个:

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

我完全忘了添加这个重要的注意事项:通过 x = iris $ Sepal.Length 使用来指定美学不是 $ 运算符!这不是使用 aes()的预期方式,它会导致错误和意外问题。

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.

这篇关于ggplot2:如何从geom_density图例中删除斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆