【问题标题】:ggplot scale_fill_discrete(breaks = user_countries) creates a second, undesired legendggplot scale_fill_discrete(breaks = user_countries) 创建第二个不想要的图例
【发布时间】:2015-09-12 11:40:00
【问题描述】:

我正在尝试更改数据框列的因子级别排序,以控制由国家名称指定的因子级别的图例排序和 ggplot 着色。这是我的数据框country_hours

  countries hours    
1    Brazil    17 
2    Mexico    13
3    Poland    20 
4 Indonesia     2 
5    Norway    20 
6    Poland    20 

这是我尝试根据所选国家/地区列表绘制数据框子集的方法,user_countries

make_country_plot<-function(user_countries, country_hours_pre)
{
  country_hours = country_hours_pre[which(country_hours_pre$countries %in% user_countries) ,]
  country_hours$countries = factor(country_hours$countries, levels = c(user_countries))            

  p = ggplot(data=country_hours, aes(x=hours, color=countries))
  for(name in user_countries){
    p = p  +   geom_bar( data=subset(country_hours, countries==name), aes(y = (..count..)/sum(..count..), fill=countries), binwidth = 1, alpha = .3)
  }
  p = p  + scale_y_continuous(labels = percent) + geom_density(size = 1, aes(color=countries), adjust=1) +
  ggtitle("Baltic countries") + theme(plot.title = element_text(lineheight=.8, face="bold")) + scale_fill_discrete(breaks = user_countries)

}

这很有效,因为着色按照我想要的顺序进行,顶部图例也是如此,但是第二个图例出现并显示不同的顺序。没有scale_fill_discrete(breaks = user_countries) 我没有得到我想要的订单,但我也没有得到两个图例。在下图中,user_countries 给出的所需顺序是

user_countries = c("Lithuania", "Latvia", "Estonia")

我想摆脱第二个传说。我该怎么做?

我还有另一个问题,就是不同地块之间的绘图/着色不一致。我希望“第一个”国家永远是蓝色的,但它并不总是蓝色的。此外,“真实”图例(较深/纯色)并不总是位于同一位置 - 有时它位于不正确/黑色图例下方。 为什么会发生这种情况,我怎样才能使这种情况在不同的情节中保持一致?

另外,不同的地块有不同数量的因子组,有时超过 9 个,所以我宁愿坚持使用标准的 ggplot 着色,因为大多数定义自己颜色的解决方案似乎限制了你可以做的颜色数量( How to assign colors to categorical variables in ggplot2 that have stable mapping?)

【问题讨论】:

  • 尝试将+ theme(legend.position="none")添加到您希望在没有图例的情况下显示的绘图定义部分。如果没有可重复的数据,我无法确定它是否有效,但我相信值得一试。

标签: r ggplot2


【解决方案1】:

您正在映射到两种不同的美学(colorfill),但您只更改了其中一种的比例规格​​。这样做总是会拆分以前组合的图例。 this page 上有一个很好的例子

为了使您的图例保持结合,除了scale_fill_discrete(breaks = user_countries) 之外,您还需要添加scale_color_discrete(breaks = user_countries)

【讨论】:

    【解决方案2】:

    我没有足够的声誉来发表评论,但这个previous question 有一个全面的答案。

    简短的回答是更改geom_density,以便它不会将国家/地区映射到颜色。这意味着只需将 aes() 中的所有内容都取出并放在外面。

    geom_density(size = 1, color=countries, adjust=1)
    

    (这应该可行。没有要确认的示例)。

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多