0

I am having trouble with excessively wide panel labels on my ggplot2 faceted plot.

Here is the code that I used to generate the plot:

png(paste("/directory/", hgnc_symbol, "_", curr_gene, ".png", sep=""),  
  width=4, height=3, units="in", pointsize=1, res=300)
  print({barplot <- 
    ggplot(curr_data, aes(x = condition, y = tpm, fill=condition)) + 
    geom_boxplot(outlier.colour=NA, lwd=0.2, color="grey18") + 
    stat_boxplot(geom ='errorbar', color="grey18") + 
    geom_jitter(size=0.8) + 
    facet_wrap(~target_id) + 
    guides(fill=FALSE) + 
    theme_bw() +  
    labs(title=paste(hgnc_symbol, "_", curr_gene, sep="")) + 
    labs(x="condition") + labs(y="TPM") + 
    theme(text = element_text(size=5), strip.background=element_rect(size = 1), 
      axis.text.x = element_text(angle = 90, hjust = 1, size=4.5))})
  dev.off()

The plot comes out looking like this:

enter image description here

As you can see, the background of the panel labels is so wide, that the plots themselves are barely visible. The points plotted on the graph are also much larger than I expected them to be.

The odd thing is that I used this same exact code to produce this following plot (which looks good) just a few days ago:

enter image description here

What is causing this difference, and how can I fix the problem?

mshum
  • 257
  • 3
  • 15
  • You can get better results when your provide some sample data. However, I think the issue is the different scales ggplot uses for plots and labels. You said you got a different result with the exact same code. I'm willing to bet you're saving the graph under different dimensions. Try increasing your width and height and see if you get a result closer to your second, more ideal graph. – oshun Jan 30 '16 at 06:46

1 Answers1

0

In ggplot, text is defined in pts, which are absolute units of measure. The plot panel is relative in size and scales according to the dimensions you specify when you save your plot. If the dimensions are small, then the text will be large relative to the panel areas. If the dimensions are large, then the text will be small relative to the panel areas. See examples below:

ggplot(diamonds, aes(x = x, y =y)) + geom_point() + facet_wrap(~ clarity)
ggsave("filepath//4x3.png", width=4, height = 3)
ggsave("filepath//8x6.png", width=8, height = 6)

The 4 x 3 in plot: 4x3.png

The 8 x 6 in plot: enter image description here

You can edit the grobs to exert finer control on the plot dimensions (example).

Community
  • 1
  • 1
oshun
  • 2,319
  • 18
  • 32
  • Thank you, @oshun; I really appreciate the explanation. Adjusting the dimensions, as you suggested in your original comment, solved the problem. – mshum Feb 02 '16 at 20:46