簡體   English   中英

R中條形圖中的某個條形如何改變顏色?

[英]How to change the colour of a certain bar in a bar chart in R?

我有以下條形圖:

當前圖

我使用以下代碼做到了這一點:

NL_population <- ggplot(data = NL, aes(reorder(Country, -`Population (g)`, sum), `Population (g)`)) + 
  geom_col(fill = "#0099f9") +
  labs(title = "Average population growth in %",
       subtitle = "Years: 2017-2021",
       x = "",
       y = "Population growth") +
  geom_hline(yintercept = mean(NL$`Population (g)`), linetype = "dashed", size = 1) + coord_flip()

我想讓荷蘭有不同於其他國家的另一種顏色。 實現這一目標的最佳方法是什么?

除了@shafee 在他的評論中提到的選項之外,一個簡單的方法是將 map 作為國家突出顯示fill aes 並通過scale_fill_manual設置所需的 colors 的條件。

使用一些基於gapminder數據集的假示例數據:

library(gapminder)
library(dplyr, warn.conflicts = FALSE)

countries <- c("Netherlands", "Italy", "Belgium", "United States", "Iceland", "Ireland")

NL <- gapminder |>
  filter(year %in% c(2007, 2002), country %in% countries) |>
  group_by(Country = country) |>
  summarise(`Population (g)` = 100 * (last(pop) / first(pop) - 1))

library(ggplot2)

ggplot(data = NL, aes(reorder(Country, -`Population (g)`, sum), `Population (g)`)) +
  geom_col(aes(fill = Country != "Netherlands")) +
  scale_fill_manual(values = c("orange", "#0099f9"), guide = "none") +
  labs(
    title = "Average population growth in %",
    subtitle = "Years: 2017-2021",
    x = "",
    y = "Population growth"
  ) +
  geom_hline(yintercept = mean(NL$`Population (g)`), linetype = "dashed", size = 1) +
  coord_flip()
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM