如何删除ggplot2图表中的边距
How to remove margins in ggplot2 chart
我目前正在使用 ggplot2 为乳胶文档创建图,发现 ggplot2 添加了许多不需要的边距:
- 被
plot.background=element_rect(fill="red")
涂成红色:
- 左侧小边距
- 图像和图例之间的小间距
- 用 photoshop 画紫色:
- 左右边距
- 1px 底部边距
删除这些边距还需要哪些规则? google 所有这些配置选项真的很难。这是我的实际图表:
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")
调整plot.margin
设置,使底部和左侧为负数。
plot.margin=unit(c(0,0,-12,-5), "mm")
如果你去掉了底部的边距,你也牺牲了图例。
您可以通过主题元素 axis.text
和 axis.tick.length
.
删除轴的其余部分 space
因此,您需要在 theme
代码中添加如下内容:
axis.text = element_blank(), axis.ticks.length = unit(0, "mm")
在 ggplot2 的当前开发版本 ggplot2_2.1.0.9001 中,有一个新的主题元素 legend.box.spacing
在这里也很有用删除图例和绘图之间的所有 space:legend.box.spacing = unit(0, "mm")
.
我目前正在使用 ggplot2 为乳胶文档创建图,发现 ggplot2 添加了许多不需要的边距:
- 被
plot.background=element_rect(fill="red")
涂成红色:- 左侧小边距
- 图像和图例之间的小间距
- 用 photoshop 画紫色:
- 左右边距
- 1px 底部边距
删除这些边距还需要哪些规则? google 所有这些配置选项真的很难。这是我的实际图表:
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")
调整plot.margin
设置,使底部和左侧为负数。
plot.margin=unit(c(0,0,-12,-5), "mm")
如果你去掉了底部的边距,你也牺牲了图例。
您可以通过主题元素 axis.text
和 axis.tick.length
.
因此,您需要在 theme
代码中添加如下内容:
axis.text = element_blank(), axis.ticks.length = unit(0, "mm")
在 ggplot2 的当前开发版本 ggplot2_2.1.0.9001 中,有一个新的主题元素 legend.box.spacing
在这里也很有用删除图例和绘图之间的所有 space:legend.box.spacing = unit(0, "mm")
.