删除ggplot2中的Plot Margins

时间:2013-07-22 11:17:03

标签: r ggplot2

我正在尝试使用ggplot2和ggsave(使用Cairo)在R中生成一个png图表。我在自定义主题以删除边距方面存在问题。

目前我正在使用:

... + theme(plot.margin=unit(c(0,0,0,0),"mm"))      

这似乎适用于我的情节的四个边中的两个边,它完全去除了顶部和右侧边缘,但左侧和底侧仍有相当大的边距。有没有办法彻底删除这些?下图说明了问题:

enter image description here

如果一个可重复的例子有用,请告诉我,我会把它们放在一起。


修改

library("ggplot2")
library("scales")
library("Cairo")
library("grid")

# Set chart values
line.width = 0.45
axis.font.size = 2.9

# Generate some random data
start.date <- as.Date("2011-07-01")
x.month <-seq.Date(start.date, by = "month", length.out = 24)
end.date <- max(x.month)

period.a <- rnorm(12, mean=50, sd=2)
period.b <- rnorm(12, mean=55, sd=2)

x.value <- c(period.a,period.b)

# Combine into dataframe
x.data <- data.frame(
  "Month" = x.month,
  "Value" = x.value
  )

# Build chart
p <- ggplot(data=x.data, aes(Month, Value)) + geom_line(size=line.width)
p <- p + theme_bw()
p <- p + scale_y_continuous()
p <- p + scale_x_date(limits=c(start.date+20,end.date-20), breaks = "1 month",labels = date_format("%b-%y"))
p <- p + theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5, size=axis.font.size),
                axis.text.y=element_text(size=axis.font.size),
                axis.title.x=element_blank(),
                axis.title.y=element_blank(),
                plot.margin=unit(c(0,0,0,0),"mm"),
                plot.background = element_rect(fill = "grey"),
                panel.grid=element_blank(),
                panel.border=element_rect(size=line.width/2),
                axis.ticks=element_line(size=line.width/3),
                axis.ticks.length=unit(0.3, "mm"),
                axis.ticks.margin=unit(0.2, "mm"))

ggsave(file="c:\\temp\\test.png", plot=p, width=40, height=15, units="mm", type ="cairo-png")

1 个答案:

答案 0 :(得分:17)

根据the source code,您还需要将标签设置为NULL,

last_plot() + labs(x=NULL, y=NULL)

或者,为左下边距设置unit(-0.5, "line")