【问题标题】:how to remove line from fill scale legend using geom_vline and geom_histogram r ggplot2如何使用 geom_vline 和 geom_histogram r ggplot2 从填充比例图例中删除线
【发布时间】:2013-02-18 18:36:50
【问题描述】:

基础知识: 使用 R 统计软件,ggplot2、geom_vline 和 geom_histogram 可视化一些数据。问题在于图例键。

我正在尝试从一些随机模拟中绘制一对直方图,并在该图之上有几条线表示确定性模拟的结果。我已经绘制了数据,但是直方图的图例键中间有一条不必要的黑线。你能帮我去掉那些黑线吗?一些重现问题的示例代码在这里:

df1 <- data.frame(cond = factor( rep(c("A","B"), each=200) ), 
                 rating = c(rnorm(200),rnorm(200, mean=.8)))

df2 <- data.frame(x=c(.5,1),cond=factor(c("A","B")))

ggplot(df1, aes(x=rating, fill=cond)) + 
  geom_histogram(binwidth=.5, position="dodge") +
  geom_vline(data=df2,aes(xintercept=x,linetype=factor(cond)),
             show_guide=TRUE) +
  labs(fill='Stochastic',linetype='Deterministic')

编辑:添加图片

干杯, 瑞恩

【问题讨论】:

    标签: r ggplot2 data-visualization legend


    【解决方案1】:

    一种解决方法是更改​​geom_histogram()geom_vline() 的顺序。然后添加另一个geom_vline() 而不添加aes(),只给出xintercept=linetype=。这不会删除线条,但会将它们隐藏在颜色图例条目下。

    ggplot(data=df1, aes(x=rating, fill=cond)) + 
      geom_vline(data=df2,aes(xintercept=x,linetype=factor(cond)),
                 show_guide=TRUE) +
      geom_histogram(binwidth=.5, position="dodge") +
      geom_vline(xintercep=df2$x,linetype=c(1,3))+
      labs(fill='Stochastic',linetype='Deterministic')
    

    【讨论】:

    • 谢谢!!!你解决了我的问题。如果你不介意,你能解释一下为什么这些线条出现在填充键中吗?我觉得奇怪的是图例键(带有黑线的红色或绿色条)与实际数据不匹配(没有线条的红色或绿色条)
    • 我不确定这种情况会发生,但我认为这与 geom_vline() 有某种联系。即使我使用具有不同级别和名称的数据框也会发生这种情况。
    • ggplot 对我来说仍然是一个美丽的谜。再次感谢。
    • 可能值得为此提交issue。我猜这可能是geom_vlineshow_guide 的错误,或者需要更多关于guides 的文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多