2016-09-23 175 views
1

考虑下面的代码:如何翻转然后放大boxplot?

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

Diamond Prices

翻转箱线图后,我怎么可以放大c(0,7000)价格(这是新的X轴)?

我觉得它与coord_cartesian(ylim=c(0, 7000)),有关,但这似乎不与coord_flip()一起使用。

回答

5

这里是我的解决方案:

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

正如论点coord_flip()结合ylim命令。

enter image description here

-1

我想你需要手动计算boxplot统计并绘制这些统计图。

# 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() 
+1

这可能会得到所需要的解决方案(我不知道提问者正是后),但由此产生的可视化将是数据的轻微虚假陈述的一些数据已被人为地“隐藏“并且显示的统计数据(例如,中位数,IQR)不是显示的数据的数据,而是其他一些数据(并非全部显示在可视化文件中)。 –

+0

我同意。对x轴进行对数转换可能是更好的解决潜在问题的方法。 –

+0

或者我今天从Thomas Pedersen看到的这个:https://twitter.com/thomasp85/status/779289579232821248 尚未发布但值得关注! –

0

您可以使用scale_y_continuous()

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

记住coord_flip()只是旋转的情节,因此你拨打scale_在Ÿ轴,这是您指定price是什么。为了这个原因,我通常喜欢最后调用它:帮助限制哪个轴是哪个轴的混淆!

+4

不过输出一个不同的boxplot。例如,上铰链现在低于5,000。 –

+0

@JanVanhove好抓。请参阅[这个问题和答案](http://stackoverflow.com/questions/38753628/ggplot-boxplot-length-of-whiskers-with-logarithmicaxis)详细说明为什么铰链会发生变化,以及如何避免它 – dww

+0

' scale_ *'不会放大绘图,只有'colim_ *'的'ylim'或'xlim'参数可以。有关更多信息,请参阅此[post](http://rpubs.com/jhofman/zoom_ggplot2)。 – yeedle