我用 ggplot 对箱线图进行了分组
require(ggplot2)
require(tidyr)
require(lubridate)
dat.1415<-as.data.frame(sample(1:1000, 181))
dat.1415$date<-seq(as.Date("2014-11-1"), as.Date("2015-4-30"), "day")
names(dat.1415)<-c("value", "date")
dat.1415$month<-month(dat.1415$date)
dat.1415$season<-"2014/15"
dat.1516<-as.data.frame(sample(1:1000, 182))
dat.1516$date<-seq(as.Date("2015-11-1"), as.Date("2016-4-30"), "day")
names(dat.1516)<-c("value", "date")
dat.1516$month<-month(dat.1516$date)
dat.1516$season<-"2015/16"
dat.1617<-as.data.frame(sample(1:1000, 181))
dat.1617$date<-seq(as.Date("2016-11-1"), as.Date("2017-4-30"), "day")
names(dat.1617)<-c("value", "date")
dat.1617$month<-month(dat.1617$date)
dat.1617$season<-"2016/17"
dat.1718<-as.data.frame(sample(1:1000, 181))
dat.1718$date<-seq(as.Date("2017-11-1"), as.Date("2018-4-30"), "day")
names(dat.1718)<-c("value", "date")
dat.1718$month<-month(dat.1718$date)
dat.1718$season<-"2017/18"
dat<-rbind(dat.1415, dat.1516, dat.1617, dat.1718)
dat$month<-month.abb[dat$month]
dat$month<-factor(dat$month)
dat$facet = factor(dat$month, levels = c("Nov", "Dec", "Jan", "Feb", "Mar", "Apr"))
ggplot(dat, aes(x=season, y=value)) +
geom_boxplot(fill="grey50") +
facet_grid(~facet) +
theme_classic()+
theme(legend.position="top") +
labs(x="", y="", title="") +
guides(fill=F) +
theme(panel.background = element_rect(fill="grey95"))
Run Code Online (Sandbox Code Playgroud)
但是因为它有太多的盒子,所以我在 x 轴上得到了重叠的标签。有没有办法让它们在不同方面之间交替?我不希望 x 轴的位置交替但实际标签,在第一个方面是“2014/15”和“2016/17”,在第 2 方面是“2015/16”和“2017/18” “ 等等。那可能吗?
尝试旋转标签以获取完整信息
+ theme(axis.text.x = element_text(angle = 30, hjust = 1))
Run Code Online (Sandbox Code Playgroud)
编辑
或者尝试以某种方式操纵您的数据并使用类似的东西
+ scale_x_discrete(breaks=c("1","3"), labels=c(...))
Run Code Online (Sandbox Code Playgroud)
Edits2:我将颜色设置为 0,以便跳过。
ggplot(dat, aes(x=season, y=value)) +
geom_boxplot(fill="grey50") +
facet_grid(~facet) +
theme_classic()+
theme(legend.position="top") +
labs(x="", y="", title="") +
guides(fill=F) +
theme(panel.background = element_rect(fill="grey95"))+
theme(axis.text.x = element_text(color=c(1,0,1,0)))
Run Code Online (Sandbox Code Playgroud)
新版本的ggplot v3.3.0guide_axis增加了使用躲避标签的功能。
scale_x_discrete(guide = guide_axis(n.dodge = 2))
因此,将其添加到您的图中:
ggplot(dat, aes(x=season, y=value)) +
geom_boxplot(fill="grey50") +
facet_grid(~facet) +
theme_classic()+
theme(legend.position="top") +
labs(x="", y="", title="") +
guides(fill=F) +
theme(panel.background = element_rect(fill="grey95")) +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
Run Code Online (Sandbox Code Playgroud)
产生以下结果:
| 归档时间: |
|
| 查看次数: |
1381 次 |
| 最近记录: |