'Adjusting white space between titles and the edge of the plot
I want to create space between the titles (the axis title and the plot title) and the edge of the plot. I tried vjust on axis.title
and plot.title
with no luck. Nothing really changed in the plot when I tried various values for vjust
. I also tried plot.margin
, but nothing seemed to happen with it either.
Data:
data = data.frame(Category = c(0,1), value = c(40000, 120000))
data$Category = factor(data$Category, levels = c(0,1), labels = c("One-time", "Repeat"))
Plot:
p = ggplot(data, aes(Category, Value)) +
geom_bar(stat = "identity", width = 0.5, position=position_dodge(width=0.9)) +
geom_text(aes(label=Value), position=position_dodge(width=0.9), family = "mono", vjust=-0.5) +
ggtitle("Title") +
scale_y_continuous(expand = c(0,0), limits = c(0,150000)) +
scale_x_discrete(expand = c(0,0), limits = c("One-time", "Repeat")) +
xlab("X axis Title") +
ylab("Y axis Title")
Theme:
p + theme(
panel.grid.major = element_line(linetype = "blank"),
panel.grid.minor = element_line(linetype = "blank"),
axis.title = element_text(family = "sans", size = 15),
axis.text = element_text(family = "mono", size = 12),
plot.title = element_text(family = "sans", size = 18),
panel.background = element_rect(fill = NA)
)
Solution 1:[1]
You want to do this using margin
p + theme(
panel.grid.major = element_line(linetype = "blank"),
panel.grid.minor = element_line(linetype = "blank"),
axis.title.x = element_text(family = "sans", size = 15, margin=margin(30,0,0,0)),
axis.title.y = element_text(family = "sans", size = 15, margin=margin(0,30,0,0)),
axis.text = element_text(family = "mono", size = 12),
plot.title = element_text(family = "sans", size = 18, margin=margin(0,0,30,0)),
panel.background = element_rect(fill = NA)
)
Note that margin requires a four inputs and they specify the space in the order top,right,bottom,left. Also note I'm using the developmental ggplot2 version so my title default is left justified. 'hjust' and 'vjust' worked in older versions of ggplot2.
Solution 2:[2]
You can also give a "-ve" value to margin argument to pull the title closer to the plot.
gg_1 +
theme(plot.title = element_text(size = 12,
hjust = 0.5,
family = fam_3,
face = "bold",
margin = margin(0,0,-10,0))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jalapic |
Solution 2 |