【问题标题】:ggplot2: how to remove slash from geom_density legendggplot2:如何从 geom_density 图例中删除斜线
【发布时间】:2014-10-07 07:28:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    试试这个:

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

    虽然这也会删除黑色轮廓...可以通过将theme 更改为:

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

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

    【讨论】:

    • @Logister 没问题。不过,请务必查看我的附加说明。
    • 感谢您的提醒。我会调整我未来的代码。
    • 太棒了!我认为 Hadley 实际上应该将其设为默认值,或者为此添加一些选项!如果 R Cookbook 专门有一个部分说明这一点:-)
    • 这在大多数情况下都有效,但如果我有多个 scale_..._...,我还没有让它工作。例如,如果我有一个 scale_fill_manual 和一个 scale_alpha_manual,那么我不能删除对角线。不知道为什么这是个问题。
    • 对我来说,在 RStudio (Windows) 中只渲染了最底部和最右边的边框,但在 ggsaveing 之后看起来与预期的一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多