I am currently creating plots with ggplot2 for a latex document and discovered that ggplot2 adds many unwanted margins:
- painted red by
plot.background=element_rect(fill="red")
:- small margin on the left
- small margin between image and legend
- painted violet with photoshop:
- margin on the left and the right
- 1px margin on the bottom
Which more rules are needed to remove these margins? It’s really difficult to google all these configuration options. This is my actual chart:
library(ggplot2)
library(scales)
label <- c("A", "B", "C", "D")
value <- c(61, 26, 9, 4)
values <- data.frame(label, value)
myplot <- ggplot(values, aes(x = "", y=value, fill=label))
myplot <- myplot + theme(legend.position="bottom")
myplot <- myplot + labs(fill="")
myplot <- myplot + geom_bar(stat="identity", width=1)
myplot <- myplot + geom_text(
aes(x=1.3, y=value/2+c(0, cumsum(value)[-length(value)])),
label=percent(value/100),
size=2
)
myplot <- myplot + coord_polar(theta="y")
myplot <- myplot + theme(plot.background=element_rect(fill="red"))
myplot <- myplot + theme(
plot.margin=unit(c(0,0,0,0), "mm"),
legend.margin=unit(0, "mm"),
axis.title=element_blank(),
axis.ticks=element_blank()
)
ggsave("pie.pdf")
2
Answers
Adjust the
plot.margin
settings so that the bottom and left side are negative numbers.plot.margin=unit(c(0,0,-12,-5), "mm")
If you do get rid of the margin on the bottom, you are also sacrificing the legend.
You can remove the rest of the axis space via the theme elements
axis.text
andaxis.tick.length
.So you’d add something like the following to your
theme
code:In the current development version of ggplot2, ggplot2_2.1.0.9001, there is a new theme element
legend.box.spacing
that could also be useful here to remove all space between the legend and the plot:legend.box.spacing = unit(0, "mm")
.