简体   繁体   中英

Geom_bar plot only shows one bar per plot

I am trying to compare two NBA players in various stats by using geom_bar but for some reason it is only plotting one bar per stat. I would like to have both bars on each plot to see how the two players compare to each other, or in other words a red and a blue on every plot

This is what I have tried

url <- paste0('https://www.basketball-reference.com/leagues/NBA_2022_per_game.html')

# scrape the url
webpage <- read_html(url)
hp_table <-
  html_nodes(webpage, "table")
nba_table <- html_table(hp_table)
# convert to dataframe
df <- as.data.frame(nba_table)
df <- df[,-1]
df

longer <- df %>% pivot_longer(-Player)

player_list <- c('Precious Achiuwa', 'Steven Adams')

filtered <- longer %>% filter(Player == player_list)

ggplot(filtered, aes(x = Player, y = value)) +
  geom_bar(aes(fill = Player),
           stat = 'identity')+
  facet_wrap(~name, scales = 'free_y')+
  theme(axis.text.x = element_blank())

每个地块一个条形图

url <- paste0('https://www.basketball-reference.com/leagues/NBA_2022_per_game.html')

# scrape the url
webpage <- read_html(url)
hp_table <-
  html_nodes(webpage, "table")
nba_table <- html_table(hp_table)
# convert to dataframe
df <- as.data.frame(nba_table)
df <- df[,-1]
df <- df %>% pivot_longer(cols = Pos:PTS) %>% 
  mutate(value = as.numeric(value)) %>% 
  filter(!is.na(value)) %>% 
  filter(Player %in% c("Precious Achiuwa", "Steven Adams"))

ggplot(df, aes(x = Player, fill = Player, y = value)) +
  geom_bar(stat = "identity", position = "dodge") + 
  facet_wrap(~name, "free_y") + 
  theme(axis.text.x = element_blank())

  • Your pivot_longer was incorrectly specified
  • Even if it was you would have had overlapping bars because you didn't specify position = "dodge" in your ggplot2 call.

阿丘瓦 vs 亚当斯

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM