[英]Fill boxplot by variable but keep date scale GGplot
我有一个数据框,其中包含三个不同日期的三个变量的值:
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()
如何让日期正确缩放并根据变量名填充?
似乎这已经在这里得到了回答。 您需要为组创建交互: group=interaction(variable,date)
:
ggplot(df,aes(x=date,y=value,group=interaction(variable,date),fill=variable))+geom_boxplot()
这个问题可以通过创建一个结合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))
由reprex 包创建于 2022-06-02 (v2.0.1)
同样可以通过在dplyr
管道中创建一个临时的新因子来完成mutate
。
suppressPackageStartupMessages({
library(ggplot2)
library(dplyr)
})
df %>%
mutate(group = interaction(date, variable)) %>%
ggplot(aes(x = date, y = value, fill = variable)) +
geom_boxplot(aes(group = group)) +
scale_x_date(
breaks = unique(df$date),
date_labels = "%Y-%m-%d"
) +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))
由reprex 包创建于 2022-06-02 (v2.0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.