Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

For reproducibility, I provide this dataset:

bball <- tibble(player = c('playerA', 'playerB', 'playerC'),
                fga = c(8, 12, 10),
                `3pa` = c(4, 2, 8),
                `2pa` = c(4, 10, 2))

It's a basketball dataset with four columns: The individual player, the field goal attempts per game, the three point field goald attempts per game and the two point field goal attempts per game. 3pa and 2pa are both counted as field goal attempts and are therefore a subset of fga (basically: 3pa + 2pa = fga). My goal is to to create a barplot with 'player' on the x-axis and 'fga' on the y-axis. But I want to fill the barplot with the respective proportions of '3pa' and '2pa'.

So far I only managed to produce this barplot, filled with only '3pa':

bball %>% 
  mutate(player = fct_reorder(player, fga)) %>% 
  ggplot(aes(player, fga, fill = `3pa`)) +
  geom_col()

barplot

But I want to display the proportions of three and two point field goal attempts in the barplot for each player. Is it possible with prior data manipulation?

question from:https://stackoverflow.com/questions/66056679/ggplot2-fill-geom-col-with-values-of-different-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to reshape the dataframe so as one column contains the variable names 2pa and 3pa, and another their values. Then you can fill using those categories.

library(ggplot2)
library(tidyr)

bball %>% 
  pivot_longer(cols = c(`2pa`, `3pa`)) %>% 
  ggplot(aes(player, value)) + 
  geom_col(aes(fill = name))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...