aaron
aaron

Reputation: 6489

Fix for overflowing x-axis text in ggplot2

I've created custom, two level x-axis entries that tend to work pretty well. The only problem is that when my y-axis, proportion, is close to one, these axis entries spill onto the chart area. When I use vjust to manually alter their vertical position, part of each entry is hidden by the chart boundary.

Any suggestions for how to make chart boundaries that dynamically adjust to accommodate large y-axis values and the full text of each entry (without running on to the chart).

Have a look at the following example:

library(ggplot2)

GroupType <- rep(c("American","European"),2)
Treatment <- c(rep("Smurf",2),rep("OompaLoompa",2))
Proportion <- rep(1,length(GroupType))
PopulationTotal <- rep(2,length(GroupType))

sampleData <- as.data.frame(cbind(GroupType,Treatment,Proportion,PopulationTotal))

hist_cut <- ggplot(sampleData, aes(x=GroupType, y=Proportion, fill=Treatment, stat="identity"))

chartCall<-expression(print(hist_cut + geom_bar(position="dodge") + scale_x_discrete(breaks = NA) +
geom_text(aes(label = paste(as.character(GroupType),"\n[N=",PopulationTotal,"]",sep=""),y=-0.02),size=4) + labs(x="",y="",fill="")
))

dev.new(width = 860, height = 450)
eval(chartCall) 

Any thoughts about how I can fix the sloppy x-axis text?

Many thanks in advance, Aaron

Upvotes: 1

Views: 818

Answers (1)

hadley
hadley

Reputation: 103898

Unfortunately you have to manage the y axis yourself - there's currently no way for ggplot2 to figure out how much extra space you need because the physical space required depends on the size of the plot. Use, e.g., expand_limits(y = -0.1) to budget a little extra space for the text.

Upvotes: 2

Related Questions