Reputation: 31
I have a problem with axis limits. My problem is that I have different dataframes to plot (i.e. bigdata and smalldata provided in the code example). I want the y-axis limit to always be greater than the maximum value.
For smalldata a limit of 50 would be great and for bigdata a limit of 150000.
Is there a way to do this automatically? I know that I can set it up with limits = c(min, max) manually.
library(ggplot2)
library(scales)
bigdata <- data.frame("variable" = c("A","B","C"), "value" = c(100000, 40000, 140000))
smalldata <- data.frame("variable" = c("A","B","C"), "value" = c(7, 1, 41))
ggplot(bigdata, aes(x = variable, y = value))+
geom_col() +
scale_y_continuous(labels = label_number())
Upvotes: 0
Views: 43
Reputation: 125143
Here is one possible option which uses a custom function to set the limits=
. In order to get pretty limits and breaks I use the option only.loose = TRUE
(see ?labeling::extended
) in scales::breaks_extended
to get a vector of extended breaks where the extreme values are chosen to lie outside of the data range, i.e. for your small data this will set the upper limit to 50, for your big data to 150000:
library(ggplot2)
library(scales)
bigdata <- data.frame("variable" = c("A", "B", "C"), "value" = c(100000, 40000, 140000))
smalldata <- data.frame("variable" = c("A", "B", "C"), "value" = c(7, 1, 41))
ggplot(bigdata, aes(x = variable, y = value)) +
geom_col() +
scale_y_continuous(
labels = scales::label_number(),
limits = \(x) range((scales::breaks_extended(only.loose = TRUE))(x))
)
ggplot(smalldata, aes(x = variable, y = value)) +
geom_col() +
scale_y_continuous(
labels = scales::label_number(),
limits = \(x) range((scales::breaks_extended(only.loose = TRUE))(x))
)
Upvotes: 1