Home > Software engineering >  Trouble with collapsing factor on y axis in ggplot 2
Trouble with collapsing factor on y axis in ggplot 2

Time:02-13

I am having a problem. My ggplot keeps collapsing two equally named vectors into one and I would like to have it as two separate bars labeled QVAR REDIHALER and the rest of the labels of course.

data.frame(
brand_name = c("QVAR REDIHALER", "QVAR REDIHALER", "XARELTO", "XIFAXAN", "LATUDA", "TRINTELLIX", "VYVANSE", "NUCYNTA"),
n = c(78, 48, 71, 26, 8, 5, 8, 1))



brand_name1 %>% 
  ggplot(mapping = aes(x = reorder(brand_name, (-n)), y = n, fill = brand_name))  
  geom_bar(stat = "identity", position = "dodge", )  
  geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1)  
  theme_bw()   
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  
  theme(plot.title = element_text(face = "bold"),
        axis.text.y = element_text(size = 14, colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank())  
  ylab("Count")  
  xlab("")  
  labs(fill = "Brand name", title = "Top Rebate Eligable - Brand")  
  scale_fill_brewer(palette = "Set2")  
  coord_flip()

The issue is where the arrow is pointed. I would like to have "QVAR REDIHALER" repeat twice as in data frame instead of it collapsing to one bar

enter image description here

CodePudding user response:

Not 100% sure about how you want to split the duplicated category into two columns. But I give it a try.

One option would be to make the duplicated categories unique by using a helper column e.g. adding a number 1, 2, ... to each and mapping this helper column on y. Doing so you get separate columns. To get rid of the numbers showing up on the axis labels you could make use of a labeller function via scale_y_discrete, i.e. use e.g. gsub to remove the numbers:

library(ggplot2)
library(dplyr)

brand_name1 <- brand_name1 %>% 
  group_by(brand_name) %>% 
  mutate(brand_name_uniq = paste0(brand_name, row_number()))

ggplot(brand_name1, mapping = aes(x = reorder(brand_name_uniq, (-n)), y = n, fill = brand_name))  
  geom_bar(stat = "identity", position = "dodge", )  
  geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1)  
  scale_x_discrete(labels = ~gsub("\\d$", "", .x))  
  theme_bw()   
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  
  theme(plot.title = element_text(face = "bold"),
        axis.text.y = element_text(size = 14, colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank())  
  ylab("Count")  
  xlab("")  
  labs(fill = "Brand name", title = "Top Rebate Eligable - Brand")  
  scale_fill_brewer(palette = "Set2")  
  coord_flip()

  • Related