Geom_bar 在一个分类变量上使用位置闪避,在另一个分类变量上使用颜色

Geom_bar with position dodge on one categorical variable and colour on another

我想根据 activity 和由 thres 指定的条形颜色或有条件地创建带有闪避条形的条形图: cpue > 75 = 'green' cpue < 75 & cpue > 50 = 'orange' cpue < 50 = 'purple'

数据示例为:

     week area_code activity  cpue  p_legal  thres thres2 
   <dbl>     <chr>    <chr>    <dbl>    <dbl>  <chr>  <chr>  
1    30      2L12  Looking      NaN      NaN  green  green  
2    31      2L12  Fishing 81.96667 90.00000  green  green  
3    31      2L12  Looking 61.32353 90.00000 orange  green 
4    32      2L12  Fishing 87.07883 80.00000  green  green  
5    32      2L12  Looking 66.99622 94.33333 orange  green 
6    35      2L12  Fishing 60.29923 86.25000 orange  green 

我知道我可以像这样使用小平面环绕:

ggplot(plot_df[plot_df$area_code == area, ]) +
  geom_bar(aes(x=week, y=cpue, fill=thres), stat='identity') +
  scale_fill_manual(values=c('green'= 'green', 'orange'='orange', 'purple' = 'purple'), guide=FALSE) +
  geom_hline(yintercept = c(50, 75)) +
  facet_wrap(~activity)

我真正想要的是闪避条,但我遇到的问题是 geom 条基于填充美学来闪避条,而颜色美学只会改变边框颜色,例如

 ggplot(plot_df[plot_df$area_code == area, ]) +
  geom_bar(aes(x=week, y=cpue, fill=activity, colour = thres), position = 'dodge', stat='identity') +
  geom_hline(yintercept = c(50, 75))

我想要与上面相同的输出,但条形颜色由概述的条件决定或 thres

当您已经使用 fill 作为一个因素时,

Facets 是附加因素的首选解决方案。如果你想用两个因素来填充,你可以尝试使用 interaction():

ggplot(plot_df[plot_df$area_code == area, ]) +
  geom_col(aes(week, cpue, fill = interaction(activity, thres)), position = "dodge")