使用coord_cartesian时在ggplot2方面设置自由y限制

时间:2019-05-02 13:25:35

标签: r ggplot2

我有一个包含三列的数据框“ data”。第一列是化合物,第二列是化合物的浓度,第三列是我的测量数据,称为“面积”。

# 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

我想使用geom_point为每个化合物创建多面图,并在完整的x轴上应用geom_smooth。为了在较低的浓度范围内进行详细研究,我应用了coord_cartesian将x轴限制为0到110。

但是,每个方面都采用给定化合物的最大值。由于化合物之间的比例差异很大,因此我不能使用固定的ylim,因为每种化合物都必须不同(在我的实际数据中,我有20多种化合物)。

是否有可能将y轴从0的最小值设置为最大值,将每面的最大值设置为可见值?

我拥有的代码(没有尝试限制y轴的方法是:

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))

1 个答案:

答案 0 :(得分:0)

我想出一种解决方法来获得想要的结果。 创建数据的子集后,我创建了一个循环以绘制所有数据。 子集数据用于确定coord_cartesian中的ylim。 使用生成的图列表,我可以使用gridExtra包在网格中对它们进行排序。

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)
}
相关问题