Home > Blockchain >  Barplot - stacked ggplot percentage barplot starting value NOT 0%
Barplot - stacked ggplot percentage barplot starting value NOT 0%

Time:06-20

I have a plot like this:

library(ggplot2)
library(reshape2)
library(ggh4x)

data <- data.frame(col1=c("Sample1","Sample2","Sample3","Sample4","Sample5","Sample6"),
                    col2=c(0.5,0.1,0.4,0.05,0.05,0.9),
                    col3=c(0.6,0.1,0.3,0.1,0.1,0.8),
                    col4=c(0.5,0.3,0.2,0.05,0.15,0.8),
                    col5=c("a","a","a","b","b","b"),
                    col6=c("c","c","c","c","c","c"))

data2 <- melt(data)

ggplot(data=data2, aes(x = variable, y = value, fill=col1)) 
  geom_bar(position="stack", stat="identity") 
  scale_fill_manual(values=c("#e6194B","#ffe119","#f58231","#911eb4","#42d4f4","#bfef45"))  
  scale_y_continuous(expand = c(0, 0),labels = scales::percent)  
  facet_nested(~col6   ~col5, scales = "free_x",space = "free_x",switch = "x")  
  ggtitle("Title")  
  theme_classic()  
  theme(strip.text.y = element_text(angle=0),legend.position = "right",
        legend.key.size = unit(0.4, 'cm'),
        axis.line = element_line(colour = "black"),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
        strip.placement = "outside",                      
        strip.background = element_rect(color = "white", fill = "white"),
        axis.title = element_blank())                    
  guides(fill=guide_legend(title=NULL, ncol = 1))  
  xlab("X axis")  
  ylab("Y axis")

Which creates a barplot like this: Please take a look

My question is simple, how can I set y-axis starting value to 10% instead of 0% (without changing the code too much). All answers are greatly appreciated! (Similar questions are checked, without success...)

CodePudding user response:

While in general not recommended for bar charts one option to "set" the starting point would be to set the limits via coord_cartesian:

library(ggplot2)
library(ggh4x)

ggplot(data = data2, aes(x = variable, y = value, fill = col1))  
  geom_bar(position = "stack", stat = "identity")  
  scale_fill_manual(values = c("#e6194B", "#ffe119", "#f58231", "#911eb4", "#42d4f4", "#bfef45"))  
  scale_y_continuous(expand = c(0, 0), labels = scales::percent)  
  facet_nested(~ col6   ~col5, scales = "free_x", space = "free_x", switch = "x")  
  ggtitle("Title")  
  theme_classic()  
  theme(
    strip.text.y = element_text(angle = 0), legend.position = "right",
    legend.key.size = unit(0.4, "cm"),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
    strip.placement = "outside",
    strip.background = element_rect(color = "white", fill = "white"),
    axis.title = element_blank()
  )  
  guides(fill = guide_legend(title = NULL, ncol = 1))  
  xlab("X axis")  
  ylab("Y axis")  
  coord_cartesian(ylim = c(.1, NA))

  • Related