仅对geom_bar中选定的条使用不同的颜色

时间:2019-01-09 05:00:22

标签: r ggplot2

我想用其他颜色突出显示中间的栏(名为SSA)。我已经尝试了可用的示例,但没有得到预期的结果。

似乎我无法正确使用ifelse元素。感谢您帮助检测错误。

与此处提供的解决方案不同,“填充”不是我数据中的一个因素:change color of only one bar in ggplot

数据:

structure(list(yield = c(48, 33, 46, 44, 79, 20, 21, 8, 40, 72, 
12, 31, 65, 10, 71, 36, 20, 60, 69, 59, 58, 49, 75, 28, 71, 61, 
34, 39, 42, 64, 47, 36, 78, 73, 51, 46, 3, 55, 70, 80, 29, 45, 
70, 72, 32, 42, 48), df = c(2, 13, 0, 9, -3, 3, 2, 0, 2, 11, 
0, 0, 5, -2, -1, -15, 0, 2, 14, 1, 6, 2, -1, 2, 8, 16, 8, 0, 
-13, 3, 0, 10, 10, -3, 7, 0, -6, 16, 0, 1, -23, 9, 11, 12, 4, 
8, 28), country = c("Angola", "Benin", "Botswana", "Burkina Faso", 
"Burundi", "Cabo Verde", "Cameroon", "Central African Republic", 
"Chad", "Comoros", "Congo, Dem. Rep.", "Congo, Rep.", "Cote d'Ivoire", 
"Equatorial Guinea", "Eswatini", "Ethiopia", "Gabon", "Gambia, The", 
"Ghana", "Guinea", "Guinea-Bissau", "Kenya", "Lesotho", "Liberia", 
"Madagascar", "Malawi", "Mali", "Mauritania", "Mauritius", "Mozambique", 
"Namibia", "Niger", "Nigeria", "Rwanda", "Sao Tome and Principe", 
"Senegal", "Seychelles", "Sierra Leone", "Somalia", "South Africa", 
"Sudan", "Tanzania", "Togo", "Uganda", "Zambia", "Zimbabwe", 
"SSA")), row.names = c(NA, -47L), class = c("tbl_df", "tbl", 
"data.frame"))

我的代码:

ggplot(arble.land, 
       aes(x = reorder(country, yield), y = yield), 
       col = ifelse(country = "SSA", "Highlighted", "Normal")) + 
  geom_bar(stat = "identity") + 
  coord_flip()  

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

  • 正如@Z_Lin所提到的,颜色部分应该在对aes的调用中。
  • if_else语句中,您应该使用==之类的逻辑运算符
  • col参数影响条形的线条颜色,您可能更喜欢fill参数

以下代码:

ggplot(arble.land, 
       aes(x = reorder(country, yield), 
           y = yield, 
           fill = ifelse(country == "SSA", "Highlighted", "Normal") )) + 
  geom_bar(stat = "identity") + 
  ## drop legend and Y-axis title
  theme(legend.position = "none", axis.title.y = element_blank()) +
  coord_flip()  

产生此图:

enter image description here

请让我知道这是否是您想要的。

更新

如果要删除左侧和右侧的“多余空间”,可以像这样在expand中使用coord_flip参数

ggplot(arble.land, 
       aes(x = reorder(country, yield), 
           y = yield, 
           fill = ifelse(country == "SSA", "Highlighted", "Normal") )) + 
  geom_bar(stat = "identity") + 
  ## drop legend and Y-axis title
  theme(legend.position = "none", axis.title.y = element_blank()) +
  coord_flip(expand = FALSE) ########## SMALL UPDATE

产生以下情节:

enter image description here