如何翻转然后放大箱线图?

How can I flip and then zoom in on a boxplot?

考虑以下代码:

library(ggplot2)
ggplot(diamonds, aes("", price)) + geom_boxplot() + coord_flip()

翻转箱形图后,如何放大到 c(0,7000) 价格(这是新的 x 轴)?

我觉得它与 coord_cartesian(ylim=c(0, 7000)) 有关系,但这似乎与 coord_flip().[=15 一起工作=]

我认为您需要手动计算箱线图统计数据并绘制它们。

# Compute summary statistics with max (y100) set to cutoff (7000)
df <- data.frame(x = 1,
             y0 = min(diamonds$price),
             y25 = quantile(diamonds$price, 0.25),
             y50 = median(diamonds$price),
             y75 = quantile(diamonds$price, 0.75),
             y100 = 7000
             )

ggplot(df, aes(x)) +
  geom_boxplot(aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
          stat = "identity") +
  coord_flip()

您可以使用 scale_y_continuous():

library(ggplot2)
ggplot(diamonds, aes("", price)) + 
  geom_boxplot() + 
  coord_flip() +
  scale_y_continuous(limits = c(0, 7000))

请记住 coord_flip() 只是旋转图,因此您在 y 轴上调用 scale_,这就是您指定 price 的内容。出于这个原因,我通常喜欢最后称呼它:以帮助减少对哪个轴是哪个轴的混淆!

这是我的解决方案:

ggplot(diamonds, aes("", price)) + 
  geom_boxplot() + 
  coord_flip(ylim=c(0, 7000))

只需将 ylim 命令组合为 coord_flip() 中的参数即可。