ggplot geom_errorbar当faceting时的宽度(和scale =“free”) [英] ggplot geom_errorbar width when faceting (and scale="free")

查看:169
本文介绍了ggplot geom_errorbar当faceting时的宽度(和scale =“free”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot和geom_errorbar创建一个分面图。但是,每个不同的方面可能具有极大不同的x范围,因此错误栏的宽度看起来并不好。这是一个MWE:

I'm trying to create a faceted plot using ggplot and geom_errorbar. However, each different facet may have have vastly different x ranges, and so the width of the error bar isn't looking "good". Here's a MWE:

library(ggplot2)
test <- data.frame( group=rep(c(1,2,3),each=10), ymin=rnorm(30), ymax=rnorm(30))
test$x <- rnorm(30) * (1+(test$group==1)*20)
ggplot( test, aes(x=x, ymin=ymin, ymax=ymax) ) +
  geom_errorbar(width=5) + facet_wrap( ~ group, scale="free_x" )
ggplot( test, aes(x=x, ymin=ymin, ymax=ymax) ) +
  geom_errorbar(width=.2) + facet_wrap( ~ group, scale="free_x" )

在第一个图中,组1的误差棒看起来不错,但是2和3太宽了。在第二个图中,组1的误差线太小。有没有简单的方法来解决这个问题?我想我可能只需要使用width = 0,但我想避免这种情况。

In the first plot, the error bars for group 1 look great, but 2 and 3 are far too wide. In the second plot, the error bars are way too small for group 1. Is there an easy way to fix this? I'm thinking I might just have to use width=0, but I'd like to avoid that.

推荐答案

解决此问题的方法是将新列添加到数据框 wd ,它包含每个级别的错误条的宽度。

Workaround for this problem would be to add to your data frame new column wd that contains width of the errorbars for each level.

test <- data.frame( group=rep(c(1,2,3),each=10), ymin=rnorm(30), ymax=rnorm(30))
test$x <- rnorm(30) * (1+(test$group==1)*20)
test$wd<-rep(c(10,0.5,0.5),each=10)

然后使用这个新的列设置 width = geom_errorbar()中。它应该在 aes()调用中设置。

Then use this new column to set width= in geom_errorbar(). It should be set inside the aes() call.

ggplot( test, aes(x=x, ymin=ymin, ymax=ymax) ) +
  geom_errorbar(aes(width=wd)) + facet_wrap( ~ group, scale="free_x" )

这篇关于ggplot geom_errorbar当faceting时的宽度(和scale =“free”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆