Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

r - ggplot2: fill geom_col with values of different columns

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...