如何在ggplot2中绘制具有正确间隔的连续x轴值的箱线图 [英] How to plot a boxplot with correctly spaced continuous x-axis values in ggplot2
问题描述
我试图绘制一个箱形图,其中我的x轴是一个连续的时间标度,该度数是度数天,即0到2500.我想获得一个x轴值在连续的时间上正确间隔的箱形图,规模,而不是离散的规模.通常,如果它是正常的时间/日期,我本可以在R中的ggplot2中使用"scale_x_date".但是,由于数字不在日期/时间范围之内,因此我不确定如何正确间隔x轴值.这是虚拟的示例:
I am attempting to plot a boxplot where my x-axis is a continuous time-scale which is growing degree days i.e. 0 to 2500. I would like to get a boxplot with x-axis values correctly spaced on a continuous time-scale rather than a discrete one. Normally if it were a regular time/date, I could have used a 'scale_x_date' with ggplot2 in R. However, since the numbers are outside date/time scale I am not sure how can we correctly space the x-axis values. Here is the dummy example:
library(ggplot2)
set.seed(1234)
#get data
df <- data.frame(y=abs(rnorm(8)),
x=as.factor(rep(c(0,100,200,500),times=2)))
ggplot(aes(y=y,x=x), data=df) +
geom_boxplot()
这给了我情节
我的x轴未根据其数值间隔.相反,我想得到一个箱形图,其中200到500之间的间距应该是100-200的三倍.我的实际数据的x轴值为0-2500个生长日.我正在寻找ggplot2特定解决方案.
where my x-axis is not spaced based on its numeric values. Instead, I would like to get a boxplot where the spacing between 200 to 500 should be three times more than 100-200. My actual data has x-axis values ranging 0-2500 growing days. I am looking for ggplot2 specific solution preferably.
推荐答案
df <- data.frame(y=abs(rnorm(8)),
x=rep(c(0,100,200,500),times=2))
ggplot(df, aes(x, y, group=x)) +
geom_boxplot()
此解决方案依赖于两个更改.首先,要绘制位于连续x轴上的框,我们需要提供数字而不是因数x值.但是,这本身并不起作用,因为在没有按因子级别对x值进行分组的情况下,ggplot不再知道如何将数据分组到不同的框中.因此,我们还需要提供一个附加的分组变量.
This solution relies on two changes. First, to plot boxes positioned on a continuous x axis, we need to provide numeric rather than factor x values. However, this does not work by itself, because without x values being grouped by factor levels, ggplot no longer knows how to group the data into different boxes. So, we also need to provide an additional grouping variable.
这篇关于如何在ggplot2中绘制具有正确间隔的连续x轴值的箱线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!