Reputation: 35331
I have a horizontal barchart, with too-tight padding:
data <- data.frame(month = factor(c("Nov", "Dec", "Jan", "Feb")),
count = c(1489, 788, 823, 1002))
g <- (ggplot2::ggplot(data, ggplot2::aes(x=month, y=count)) +
ggplot2::geom_col() +
ggplot2::scale_x_discrete(limits=rev(data$month)) +
ggplot2::coord_flip()) +
g
I am happy with the spacing between the bars, but I want a lot more space all around the 4-bar stack. In other words, I want more padding around the central 4-bar figure. The area of the light-gray rectangle that serves as the background for the 4-bar stack should remain unchanged, but the size of the 4-bar stack within that rectangle should shrink, with the net effect of produing wider padding all around the 4-bar stack; in other words, more of the light-gray background will be visible around the 4-bar stack.
Also, I am looking for ways to do this that are entirely independent of the actual values on the axes. The code should produce the same visual effect whether the x-range is 0-1500 or 0-1500000 or altogether non-numeric (i.e. categorical).
This means that the extra padding must be specified either (a) as percentages for the figure's total width and height; or (b) fixed numbers of pixels; or (c) fixed units of measurement (cm, inches, printer points, etc.).
Lastly, ideally, I would like to be able to specify the padding for all four edges independently.
How can I do this?
IMPORTANT I don't want to increase the margins around the light gray background. I want to increase the padding within the light gray background. If this distinction is not clear, please see this.
Upvotes: 1
Views: 1943
Reputation: 3448
You can use the expand_scale
function within the expand
argument to scale_x_continuous
-type functions. It's a bit wordy, but...
ggplot(data, aes(x=month,y=count)) +
geom_bar(stat="identity") +
scale_x_discrete(limits=(data$month), expand=expand_scale(mult=c(0.5,0.5))) +
geom_text(aes(label=count), hjust=-0.3) +
coord_flip() + scale_y_continuous(expand=expand_scale(mult=c(0.5,0.5)))
Play around with the two elements of the mult
vector, which define the padding above and below the axis, so you can change each side of the plot independently (although it's not exactly transparent, and will take some fiddling). See ?expand_scale
for more info.
Upvotes: 2