我在ggplot中做了一些带有三个变量的箱形图并且很长时间没有得到我想要的东西,因为我x轴上的数据是数字而不是因子 . 在阅读文档(http://www.sthda.com/english/wiki/ggplot2-box-plot-quick-start-guide-r-software-and-data-visualization)和其他问题(Modify x-axis labels in each facetggplot: arranging boxplots of multiple y-variables for each group of a continuous x)后,我明白我必须将x轴数据转换为因子 .

> str(HT_2)
Classes ‘data.table’ and 'data.frame':  540 obs. of  4 variables:
 $ T             : int  -1 -2 -3 -4 0 1 2 3 4 -1 ...
 $ Month         : Factor w/ 12 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Gauge         : chr  "Aconcagua" "Aconcagua" "Aconcagua" "Aconcagua" ...
 $ Norm_Flow_m3_s: num  1.49 1.77 1.99 2.02 1.17 ...
 - attr(*, ".internal.selfref")=<externalptr>

以下代码行解决了我的问题

ggplot(HT_2, aes(x=Month, y=Norm_Flow_m3_s,fill=Gauge)) + geom_boxplot()

但是当x轴具有int数据时,同一行失败

> str(HT_2)
Classes ‘data.table’ and 'data.frame':  540 obs. of  4 variables:
 $ T             : int  -1 -2 -3 -4 0 1 2 3 4 -1 ...
 $ Month         : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Gauge         : chr  "Aconcagua" "Aconcagua" "Aconcagua" "Aconcagua" ...
 $ Norm_Flow_m3_s: num  1.49 1.77 1.99 2.02 1.17 ...
 - attr(*, ".internal.selfref")=<externalptr> 
 - attr(*, "sorted")= chr "Month"

即使我尝试将我的x轴数据分组

ggplot(HT_2, aes(x=Month, y=Norm_Flow_m3_s,fill=Gauge,group=Month)) + geom_boxplot()

有谁知道为什么会这样?或者我如何在箱形图中包含数字数据?