I have the following ggplot:
that is generated using the following script:
df_long <- melt(df)
ggplot(df_long, aes(x = variable, y = value))
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.
my_breaks <- function(x){seq(0, max(x), length.out = 5)}
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 ;)