Spencer Trinh
Spencer Trinh

Reputation: 783

Expand a congested x axis in ggplot2

I made a ggplot that has 86 items on each axis. I am trying to adjust the text labels/ticks so that it can be properly read. At the moment I can only produce a plot that does not provide enough space for the text on the x axis. Please see photo.

photo

Here are selected values from the dataframe that is being plotted:

     Var1 Var2     value   group
1       1    1 1.0000000 Group 1
2       2    1 0.7086322 Group 1
1654   20   20 1.0000000 Group 2
1657   23   20 0.7037037 Group 2
2524   30   30 1.0000000 Group 3
2526   32   30 0.8466508 Group 3
4177   49   49 1.0000000 Group 4
4186   58   49 0.7201761 Group 4
5830   68   68 1.0000000 Group 5
5837   75   68 0.8125000 Group 5
6700   78   78 1.0000000 Group 6
6701   79   78 0.8402689 Group 6

This is what I have so far:

assign.colour<-c("#8DA0CB","#66C2A5","#A6D854","#E5C494","#E78AC3","#FC8D62")
p<-ggplot(data=df,aes(Var1,Var2)) + geom_tile(data=df,aes(fill=group),color="grey")+
  scale_fill_manual(values = assign.colour)+
  theme(axis.text.x=element_text(angle=45,margin = margin(1, unit = "cm")))+
  scale_x_discrete(position="top")
p

I also tried expand=c(0,0) but it didn't do anything. I tried hjust=-0.1 and it moved the labels above the border of plot but the spacing was still too tight for reading. Any help would be appreciated.

Upvotes: 2

Views: 6367

Answers (2)

Koundy
Koundy

Reputation: 5513

Try adding this

theme(axis.text.x=element_text(angle=90,margin = margin(1, unit = "cm"),vjust =1))

or you can adjust size in element_text

theme(axis.text.x=element_text(angle=45,size = rel(0.5), margin = margin(1, unit = "cm"),vjust =1))

lastly, save your plot as image with larger size.

Upvotes: 3

Have you tried working on the plotting device dimensions?

If it is pdf,

pdf( "output.pdf", width = xx, height = yy )

Please refer the following for tick spaces as well:

Change distance between x-axis ticks in ggplot2

Upvotes: 1

Related Questions