Home > OS >  set y-axis range to be /-10 percentage points of data in R
set y-axis range to be /-10 percentage points of data in R

Time:09-17

I am plotting multiple (~300) bar graphs and would like to fix the y-axis range at between /- 10 percentage points of data in my dataset. Eg: if the y-axis range in my data set is (10,20), I'd like to display the graph rage as (0,30). Any idea how to do this easily across all plots? Thanks

CodePudding user response:

Based on your question, you're looking to expand the y axis by /- 10 percent; however, inside the text of your question it seems you need to expand by /- 10 units (whatever your units of the y axis happen to be). You can do either quite easily using expansion(), which can be applied to scale_y_continuous() via the expand = argument. Here's an example plot.

library(ggplot2)

df <- data.frame(x=LETTERS[1:4], y=c(10, 20, 30, 25))

p <- ggplot(df, aes(x,y))   geom_col()

The limits of the data in y are [10, 30] as stated in your question. If you want to automatically expand those by 10 units in either direction, you need to apply expansion(add = (...)) to the expand= argument in scale_y_continuous(). In the enter image description here

If you want to keep the lower limit the same and only add to the y axis (by 15 in this case), you specify a vector with 2 numbers:

p   scale_y_continuous(expand = expansion(add = c(0,15)))

enter image description here

If you want to expand by a percentage, you can specify mult= instead of add=. This takes the number or numbers assigned to mult= and multiples that by the highest or lowest value in your plot. So, to expand by 10% in either direction, you multiply by 0.1:

p   scale_y_continuous(expand = expansion(mult = 0.1))

enter image description here

  • Related