Home > database >  Geom_bar plot only shows one bar per plot
Geom_bar plot only shows one bar per plot

Time:08-28

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())

one bar per plot

CodePudding user response:

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.

Achiuwa vs Adams

  • Related