简体   繁体   中英

Change the y-axis limits in a ggplot of multiple plots

I have the following ggplot:

在此处输入图片说明

that is generated using the following script:

df_long <- melt(df)

ggplot(df_long, aes(x = variable, y = value)) + 
  geom_boxplot() +
  facet_wrap(~variable, scales = 'free', ncol = 6)

I would like to change the y-axis limits to start with 0 and end with the maximum value for each variable, and also to have the same breaks for all the variables. Currently, the AC and ND are fine since they have same breaks (their labels are even aligned) but the other variables are different. For the NV and IC , they don't end with the maximum value and they don't have the same breaks as with AC and ND . For the PIC and DBI , they don't have the same breaks as with AC and ND . In other woeds, I want all y axes to be aligned and look elegant.

Do you have any idea how to fix that?

You need to specify your requirements for the y axis and set it up with the scale_y_continuous statement.

The breaks argument can be a function returning breaks from the given data, so you can set up a function to give a sequence of set length between its min and max values. Note that these axis values may not make much sense (eg. 2.09, 2.83, ...) but they will be at the same y positions on the graph.

The selected break values are pretty unreadable so we can also specify a function for the labels argument that takes the breaks as input and returns the rounded labels.

library(ggplot2)
# generate dummy data
set.seed(2)
df <- data.frame(var = sample(LETTERS[1:4], 1000, replace = T),
                 val = abs(rnorm(1000)))
df$val[df$var%in%c("B", "D")] <- df$val[df$var%in%c("B", "D")] / 2 
head(df)


# actual plotting
my_breaks <- function(x){seq(min(x), max(x), length.out = 5)}
my_labels <- function(x){round(x, digits = 2)}

ggplot(df, aes(x=var,y=val)) + geom_boxplot() + facet_wrap(~var, scales = 'free', ncol = 4) +
  scale_y_continuous(breaks = my_breaks, labels = my_labels)

This outputs the following graph

在此处输入图片说明

EDIT : adding some constraints to the axes

If you want to restrain your axes to specific ranges, you have to play around with the my_breaks() function definition. I'll give you a few examples below as per your comments.

  • Start the axes on 0 : my_breaks <- function(x){seq(0, max(x), length.out = 5)}
  • End the on 1 or max value if smaller : my_breaks <- function(x){seq(min(x), min(1, max(x)), length.out = 5)}

I'm sure you can figure out the specific requirements to your needs ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM