Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate tick labels in grouped ggplot to avoid overlap in R

Tags:

r

ggplot2

I have grouped boxplots with 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"))

Grouped boxplots

But because it's so many boxes, I get overlapping labels on the x-axis. Is there a way I can make them alternating between the different facets? I don't want the position of the x-axis to alternate but the actual labels, say in facet one it's "2014/15" and "2016/17", in facet 2 it's "2015/16" and "2017/18" and so on. Is that possible?

like image 879
Anke Avatar asked Oct 18 '25 06:10

Anke


1 Answers

try to rotate you labels to have full information

+ theme(axis.text.x = element_text(angle = 30, hjust = 1)) 

Edits

Or try to manipulate your data somehow and use something like

+ scale_x_discrete(breaks=c("1","3"), labels=c(...))

Edits2: I set the color to 0 for the ones to skip.

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))) 

enter image description here

like image 130
Bing Avatar answered Oct 19 '25 22:10

Bing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!