2013-07-22 118 views
24

我正尝试在R中使用ggplot2和ggsave(与开罗)来生成png图表。我在定制主题以消除边距时遇到问题。删除ggplot2中的绘图边距

目前我使用:

... + 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") 

回答

17

the source code,你还需要将这些标签设置为NULL,

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

或者,底部和左侧距设置unit(-0.5, "line")

+4

是或''xlab(NULL)''来控制一个标签。像''axis.title.x = element_blank()''一样,更常见的''xlab(“”)''移除文本,但不移除空格afaik。事实上,跟在baptiste的链接上,第56行证实了这一点:“if(is.null(labels $ x))unit(0,”lines“)else unit(0.5,”lines“)' – PatrickT

+0

这也可能帮助:http://stackoverflow.com/questions/22945651/how-to-remove-space-between-axis-area-plot-in-ggplot2 –