我有一個資料框,其中包含三個不同日期的三個變數的值:
df <- data.frame(date = as.Date(c(rep('2021-01-01',6),rep('2021-05-04',6),rep('2015-04-04',6))),
variable = rep(c('apple','bananna','carrot'),6),
value = rnorm(18,5,2))
我想制作一個箱線圖,其填充與變數、x 軸上的日期和 y 軸上的值有關:
ggplot(df,aes(x=as.factor(date),y=value,fill=variable)) geom_boxplot()
這基于變數填充,但它不會根據實際的時間差異縮放日期:

如果我設定group=date,它會正確縮放,但fill=variable停止作業:
ggplot(df,aes(x=date,y=value,group=date,fill=variable)) geom_boxplot()

如何讓日期正確縮放并根據變數名填充?
uj5u.com熱心網友回復:
這個問題可以通過創建一個結合date和的因子變數來解決variable。這是用interaction.
我還添加了代碼來增加繪圖視窗的寬度,以使條形圖和標簽更明顯。
df <- data.frame(date = as.Date(c(rep('2021-01-01',6),rep('2021-05-04',6),rep('2015-04-04',6))),
variable = rep(c('apple','bananna','carrot'),6),
value = rnorm(18,5,2))
library(ggplot2)
x11(width = 20, height = 8) # this is not stricktly needed
ggplot(df, aes(x = date, y = value, fill = variable))
geom_boxplot(aes(group = interaction(date, variable)))
scale_x_date(
breaks = unique(df$date),
date_labels = "%Y-%m-%d"
)
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))

由
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/485233.html
上一篇:R:如何自定義情節互動懸停視窗?
