Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set free y limits in ggplot2 facets while using coord_cartesian

Tags:

r

ggplot2

I have a data frame 'data' with three columns. The first column identifies the compound, the second the concentration of the compound and the third my measured data called 'Area'.

# A tibble: 12 x 3
   Compound    Conc     Area
   <chr>      <dbl>    <dbl>
 1 Compound 1     0      247
 2 Compound 1     5    44098
 3 Compound 1   100   981797
 4 Compound 1  1000  7084602
 5 Compound 2     0      350
 6 Compound 2     5   310434
 7 Compound 2   100  6621537
 8 Compound 2  1000 49493832
 9 Compound 3     0       26
10 Compound 3     5     7707
11 Compound 3   100   174026
12 Compound 3  1000  1600143

I want to create a facetted plot per compound using geom_point & apply geom_smooth on the complete x axis. To look into detail in the lower concentration range I applied coord_cartesian to limit the x axis from 0 to 110.

However, each facet takes the maximum value of the given compound. As the scales are very different between compounds I can't use a fixed ylim as it would have to be different for each compound (in my real data I have > 20 compounds).

Is there a possibility to set the y-axis from 0 as minimum and as maximum per facet the maximal value which is visible?

The code I have (without any tries on limiting the y-axis is:

ggplot(data = data, aes(Conc, Area)) +
  geom_point(size = 2.5) +
  geom_smooth(method = "lm") +
  facet_wrap(~Compound, ncol = 3, scales = "free_y") +
  theme_bw() +
  theme(legend.position = "bottom") + 
  coord_cartesian(xlim = c(0,110))
like image 663
Philippe Vervliet Avatar asked Jul 13 '26 01:07

Philippe Vervliet


1 Answers

I figured out a workaround to get the results I want. After creating a subset of the data I created a loop to plot all the data. The subsetted data was used to determine the ylim in coord_cartesian. With the resulting plot list I can use the gridExtra package to sort them in a grid.

data_100 <- data %>% 
  filter(Conc <= 110)

loop.vector <- unique(data$Compound)

plot_list = list()

for (i in seq_along(loop.vector)) { 

  p = ggplot(subset(data, data$Compound==loop.vector[i]),
           aes(Conc, Area)) + 
    geom_point(size=2.5) +
    geom_smooth(method = "lm", se = FALSE) +
    theme_bw() +
    theme(legend.position="bottom") +
    coord_cartesian(xlim = c(0,110),
                    ylim = c(0, max(data_100$Area[data_100$Compound==loop.vector[i]]))) +
    labs(title = loop.vector[i])

  plot_list[[i]] = p

  print(p)
}
like image 97
Philippe Vervliet Avatar answered Jul 15 '26 13:07

Philippe Vervliet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!