Sadaf
Sadaf

Reputation: 163

Grouped plots and setting limits of vertical axis different for all variables in R

I want to set the limits of vertical axis differently say of Prof (0,0.5) and of sal(0,2) and of logging(0,3). I am using the following codes

set.seed(123)
ID = rep(c("BAU","IMP","SGR","CR"), each=5000)
Time = rep (c(1:1000), each = 20)
data <- data.frame( ID, Time,  profits = runif(20000,0,1), Salinity= runif(20000,3,4), Logging=runif(20000,0.05,3))
DF <- data %>% 
  group_by(Time, ID) %>% 
  summarise(Sal = mean(Salinity), 
            Logg = mean(Logging), 
            profs = mean(profits)) %>% 
  gather(type, value, c(Sal, Logg, profs))


ggplot(DF, aes(x=Time, y = value, color =ID)) +
  geom_line(size=1) + facet_grid(~ID) +
 facet_wrap(~type, scales ="free", ncol =1) + 
  theme_classic() +  theme(legend.position="top")+ 
  # theme_light() + 
  labs(title ="Baseline experiment", x ="Seasonsal time steps", y = "Value")

Thanks for the help.

Upvotes: 1

Views: 97

Answers (1)

stefan
stefan

Reputation: 123938

If you only want each scale to start at 0 you could do so by scale_y_continuous(limits = c(0, NA)). Otherwise one option to achieve your desired result would be to make use of the ggh4x package which allows you to set the limits, breaks, ... of a positional scale per facet:

library(ggplot2)
library(dplyr)
library(tidyr)

p <- ggplot(DF, aes(x = Time, y = value, color = ID)) +
  geom_line(size = 1) +
  facet_wrap(~type, scales = "free", ncol = 1) +
  theme_classic() +
  theme(legend.position = "top") +
  labs(title = "Baseline experiment", x = "Seasonsal time steps", y = "Value")

p + scale_y_continuous(limits = c(0, NA))

library(ggh4x)

scales <- lapply(
  list(Logg = c(0, 3), profs = c(0, 1), Sal = c(0, 4)),
  function(limits) scale_y_continuous(limits = limits)
)

p + facetted_pos_scales(y = scales)

Upvotes: 1

Related Questions