首页 文章

ggplot scale_fill_discrete(breaks = user_countries)创建第二个不受欢迎的图例

提问于
浏览
0

我正在尝试更改数据框列的因子级别排序,以控制由国家/地区名称指定的因子级别的图例排序和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")

enter image description here

I'd like to get rid of this second legend. How can I do it?

我还有另一个问题,即不同图之间的绘图/着色不一致 . 我'd like the 2566393 country to always be blue, but it'并不总是蓝色 . 另外'real'传奇(深色/纯色)并不总是在同一个位置 - 有时它低于不正确/黑色的图例 . Why does this happen and how can I make this consistent across plots?

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

2 回答

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

    (这应该有效 . 没有一个例子可以确认) .

相关问题