3

I am trying to control the range of the y-axis in a bar plot using ggplot. For this graph, I would like to the set the y-axis origin at 1, and not at 0 as ggplot2 does by default.

For this example, lets assume I want to plot the median value for a scale ranging from 1 to 7, and I would like to set the range of the y-axis as such. (A working example is shown below).

If I just create a bar plot using geom_bar, the origin for the y-axis is set automatically at zero.

If I use scale_y_continuous(limits=c(1,7)) to set the limits for the y-axis, no bar is plotted.

If I use scale_y_continuous(limits=c(1,7), oob=rescale_none), the y-axis ranges from 1 to 7 but it is like the bar starts to be plotted from zero, making the plot aesthetically not ideal (there is not margin between the bars and the bottom border of the graph.

Here is a working example (sorry for the lack of graphs; I am not allow to post them due to my insufficient reputation):

library(ggplot2)
library(scales)

# Creating "dataset"
dt <- data.frame(a=c("A", "B", "C"),
                 b=c(3, 5, 1))

# Default y-axis range, internaly set by ggplot
ggplot(dt, aes(x=a, y=b)) + theme_bw() +
  geom_bar(stat="identity")


# Simply using 'limits'. Breaks expected in y=c(1,3,5,7)
# Bars not graphed
ggplot(dt, aes(x=a, y=b)) + theme_bw() +
  geom_bar(stat="identity") + 
  scale_y_continuous(limits=c(1,7), breaks=c(1,3,5,7))


# Using 'oob' from package:scales
# Bars are shown, breaks in the right place, 
# but bars start running from y=0 (not beautiful)
ggplot(dt, aes(x=a, y=b)) + theme_bw() +
  geom_bar(stat="identity") + 
  scale_y_continuous(limits=c(1,7), breaks=c(1,3,5,7), oob=rescale_none)
FabF
  • 61
  • 5

0 Answers0