如何在R中为ggplot2中的堆叠条形图分配唯一的颜色?

fzsnzjdm  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(183)

我正在尝试更改GGplot 2中堆叠条形图的颜色。我希望每个'possession_abbr'的顶部条形图都是'grey',并且我希望所有'possession_abbr'的底部颜色都是唯一的。我的数据中已经有一个名为'team_color'的列,其中包含所有'possession_abbr'的唯一颜色。我如何用每个唯一颜色填充每个底部条形图?
以下是我尝试过的:

stack <- ggplot(d, aes(x=possession_abbr, y=count, fill=run_pass ) )+
  geom_col(position = "fill") +
  scale_fill_manual(values = c("grey", d$team_color) ) +
  scale_y_continuous(labels = scales::percent) +
  labs(title = "Proportion of Pass and Run Plays for Each Team", 
       subtitle = "(2022 Season)", x= "", y= "Proportion of Plays",
       fill = "Run or Pass")

下面是结果图:

我的代码似乎用d$team_color中找到的第一个颜色填充底部的条。我如何为每个团队获得每个唯一的颜色?
我被困了一段时间。任何帮助都非常感谢!

wlwcrazw

wlwcrazw1#

将一个变量Map到fill上的两个类别会给予你两种颜色。就是这样。相反,将possession_abbrrun_pass的交互Map到fill aes上。第二,用你的团队颜色和相同数量的grey创建一个调色板。第三,根据团队名称或更准确地根据possession_abbrrun_pass的交互来命名此调色板。最后,对于图例,我只显示第一个灰色和第一个彩色类别,我使用breaks参数。
使用一些假随机示例数据:

library(ggplot2)

set.seed(123)

d <- data.frame(
  possession_abbr = LETTERS,
  run_pass = rep(c("run", "pass"), each = 26),
  count = runif(26 * 2)
)
d <- transform(d, fill = paste(possession_abbr, run_pass, sep = "."))

# Team colors
team_color <- scales::hue_pal()(26)
# Team names
team_names <- unique(d$possession_abbr)

# Color palette
pal_color <- c(team_color, rep("grey", 26))
# Name the color palette
names(pal_color) <- c(
  paste(team_names, "run", sep = "."),
  paste(team_names, "pass", sep = ".")
)

ggplot(d, aes(x = possession_abbr, y = count, group = run_pass, fill = fill)) +
  geom_col(position = "fill") +
  scale_fill_manual(values = pal_color, breaks = c("A.pass", "A.run"), labels = c("pass", "run")) +
  scale_y_continuous(labels = scales::percent, expand = c(0, 0)) +
  labs(
    title = "Proportion of Pass and Run Plays for Each Team",
    subtitle = "(2022 Season)", x = "", y = "Proportion of Plays",
    fill = "Run or Pass"
  ) +
  theme_minimal()

相关问题