Search code examples
rggplot2bar-chartggbreak

How to truncate y-axis not from zero in ggplot2?


In R, I tried the following code for bar chart. I want to truncate y-axis and make it start not from zero, I tried 'coord_cartesian', but it failed. I was wondering if there is better way to do this?

library(ggplot2)
library(ggbreak)

data <- data.frame(
  category = c("A", "B", "C"),
  value = c(2, 20, 18)
)

ggplot(data, aes(x=category, y=value, fill=category)) + 
  geom_col() +
  theme_minimal() +
  labs(x="Type", y="Value")+
  scale_y_break(c(3,15),
                scales=1,
                space=1,
                expand = c(0,0))+
  coord_cartesian(ylim = c(1, 20))

enter image description here


Solution

  • This creates a very bad plot. A barplot starts always at 0. But you can do this with geom_linerange.

    ggplot(data, aes(x=category, ymin = 1, ymax = value, color=category)) + 
      geom_linerange(linewidth = 60) +
      theme_minimal() +
      labs(x="Type", y="Value")+
      scale_y_break(c(3,15),
                    scales=1,
                    space=1,
                    expand = c(0,0)) +
      guides(color = guide_legend(override.aes =list(linewidth = 6)))
    

    resulting plot