我想绘制连续变量和分类变量(geom_boxplotggplot2)之间的关系的箱线图,这在几种情况下(facet_wrap)。很简单:

data("CO2")
ggplot(CO2, aes(Treatment, uptake) ) +
  geom_boxplot(aes(Treatment, uptake),
               col="black", fill="white", alpha=0, width=.5) +
  geom_point(col="black", size=1.2) +
  facet_wrap(~Type, ncol=3, nrow=6, scales= "free_y") +
  theme_bw() +
  ylab("Uptake")

结果:
r - 如何协调facet_wrap中的轴并缩放="free_y"?-LMLPHP

这个玩具数据集非常不错,但是应用于我自己的数据(facet_wrap使我能够绘制18个不同的图)y轴几乎不可读,其y标记的数量不同并且它们之间的间距也不同:

r - 如何协调facet_wrap中的轴并缩放="free_y"?-LMLPHP

协调y轴的最佳方法是什么? (即,无论是什么中断,y轴刻度之间的间距都是相等的-由于我的连续变量的变化范围变化很​​大,因此这些位置必定会从一个图变为另一个图

非常感谢您的帮助:)

最佳答案

通过在y轴值上应用pretty()并扩展第一个值/最后一个值,可以手动扩展每个构面的值,从而可以将每个构面的限制强制为相对漂亮的外观。

以下是使用Diamonds数据集的示例:

# normal facet_wrap plot with many different y-axis scales across facets
p <- ggplot(diamonds %>% filter(cut %in% c("Fair", "Ideal")),
       aes(x = cut, y = carat) ) +
  geom_boxplot(col="black", fill="white", alpha=0, width=.5) +
  geom_point(col="black", size=1.2) +
  facet_wrap(~clarity, scales= "free_y", nrow = 2) +
  theme_bw() +
  ylab("Uptake")

p

r - 如何协调facet_wrap中的轴并缩放=&#34;free_y&#34;?-LMLPHP
# modified plot with consistent label placements
p +
  # Manually create values to expand the scale, by finding "pretty"
  # values that are slightly larger than the range of y-axis values
  # within each facet; set alpha = 0 since they aren't meant to be seen
  geom_point(data = . %>%
               group_by(clarity) %>% #group by facet variable
               summarise(y.min = pretty(carat)[1],
                         y.max = pretty(carat)[length(pretty(carat))]) %>%
               tidyr::gather(key, value, -clarity),
             aes(x = 1, y = value),
             inherit.aes = FALSE, alpha = 0) +

  # Turn off automatical scale expansion, & manually set scale breaks
  # as an evenly spaced sequence (with the "pretty" values created above
  # providing the limits for each facet). If there are many facets to
  # show, I recommend no more than 3 labels in each facet, to keep things
  # simple.
  scale_y_continuous(breaks = function(x) seq(from = x[1],
                                              to = x[2],
                                              length.out = 3),
                     expand = c(0, 0))

r - 如何协调facet_wrap中的轴并缩放=&#34;free_y&#34;?-LMLPHP

关于r - 如何协调facet_wrap中的轴并缩放="free_y"?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52102058/

10-12 18:10