Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the margin and change the font style for labels in ggplot

Tags:

r

ggplot2

I have generated a dendrogram using ggdendro and ggplot. I have two issues regarding the generated plot.

  1. Is that possible to cut some margin from the generated plot?
  2. How to change the font style, e.g., size, for the label along one axis?

In the plot, the two areas marked by "red pane" are the margins I would like to remove. The six labels along the x-axis is marked with yellow color. I would like to increase the size of them.

enter image description here

The code:

> x<-read.csv("test1.csv",header=TRUE)
> d<-as.dist(x,diag=FALSE,upper=FALSE)
> hc<-hclust(d,"ave")
> dhc<-as.dendrogram(hc)
> ddata<-dendro_data(dhc,type="rectangle")
> ddata$labels$text <- gsub("\\."," ",ddata$labels$text)
> fig1<-ggplot(segment(ddata))+geom_segment(aes(x=x0,y=y0,xend=x1,yend=y1))
> fig1<-fig1+xlab(NULL)+ylab(NULL)+opts(panel.grid.minor=theme_blank())
> fig1<-fig1+scale_x_discrete(limits=ddata$labels$text)
> fig1<-fig1+coord_flip()
> last_plot()
> fig1<-last_plot()
> ggsave("test1.pdf")
like image 791
bit-question Avatar asked Dec 09 '11 03:12

bit-question


1 Answers

To increase the size of the axis labels (and much, much more) you use theme (in older versions of ggplot2 this was called opts()):

+ theme(axis.text.x = element_text(size = 12))

will make them much bigger. For reducing the margins, you'll may want to use the expand argument:

+ scale_x_continuous(expand = c(0,0))

where the numbers are the additive and multiplicative expansion factors for the plot limits.

More generally, these things are all quite well documented at locations like here or here. Or you could just buy Hadley's book, which will answer nearly every ggplot question you'll have. (Seriously.)

like image 97
joran Avatar answered Nov 15 '22 01:11

joran