Home > Enterprise >  Error filling and distributing values on the x-axis of the bar graph
Error filling and distributing values on the x-axis of the bar graph

Time:11-03

I'm trying to create a bar graph in ggplot, considering a "type" variable in the filling of each bar.

However, the maximum values of the bars are excessively high (above 100, when in fact they should be close to 40). My goal is to place the overlay padding.

I appreciate any help.

df <- structure(list(Count = c("Beu", "Beu", "Beu", "Abe", "Abe", "Abe", 
"Pre", "Pre", "Pre", "Bra", "Bra", "Bra"), Type = c(1, 2, 3, 
1, 2, 3, 1, 2, 3, 1, 2, 3), Hours = c(40.17775, 42.1492178098676, 
42.1910353866317, 38.3701812919564, 39.9185282522996, 38.8002722361139, 
41.6389448017412, 41.7041742286751, 41.9545826200271, 41.1375910844406, 
41.0602923264312, 40.6300999927013)), row.names = c(NA, 12L), class = "data.frame")

Here's the code I'm trying to run:

df %>% 
  mutate(Type = as.factor(Type)) %>% 
  ggplot(mapping = aes(x = Count, y = Hours, fill = Type))  
  geom_bar(stat = 'identity')  
  coord_flip()  
  theme_classic()

CodePudding user response:

To overlay the bars you could add position = 'identity' in your geom_bar with a lower transparency alpha like this:

library(ggplot2)
library(dplyr)
df %>% 
  mutate(Type = as.factor(Type)) %>% 
  ggplot(mapping = aes(x = Count, y = Hours, fill = Type))  
  geom_bar(stat = 'identity', position = 'identity', alpha =0.2)  
  coord_flip()  
  theme_classic()

Another option is by dodging your bars using position_identity to have them overlayed and to make sure the highest values are behind you can arrange the values per group like this:

df %>% 
  mutate(Type = as.factor(Type)) %>% 
  group_by(Count) %>%
  arrange(desc(Hours)) %>%
  ggplot(mapping = aes(x = Count, y = Hours, fill = Type))  
  geom_bar (stat="identity", position =position_identity())  
  coord_flip()  
  theme_classic()

Created on 2022-11-02 with enter image description here

  • Related