在ggplot2中设置base_size时重叠轴标签

时间:2011-09-27 09:51:19

标签: r ggplot2 label

我正在通过base_size更改theme_set。当我在屏幕上查看结果图时,它看起来很棒。但是,当我将其保存为pdf时,x轴标签有点太靠近轴编号。

一件小事:

 theme_set(theme_bw(base_size = 9))

不会导致任何问题,但

 theme_grey(theme_bw(base_size = 9))

一样。这是一个示例图表:

enter image description here

R代码

require(ggplot2)
theme_set(theme_bw(base_size = 9))

#Data
m = c(0.475, 0.491, 0.4800, 0.4318, 0.4797, 0.5718)
m = c(m, 0.00252, 0.00228, 0.00254, 0.00291, 0.00247, 0.00201)
m = c(m, 0.306, 0.260, 0.3067, 0.3471, 0.3073, 0.2357)

s = c(0.0172, 0.0681, 0.0163, 0.0608, 0.0170, 0.1088)
s = c(s, 0.000087, 0.000367, 0.000091, 0.000417, 0.000094, 0.000417)
s = c(s, 0.0092, 0.0447, 0.0110, 0.0593, 0.0113, 0.0504)

df = data.frame(m=m, s=s)

df$data_set = as.factor(c("Data set 1", "Data set 2"))
df$est = factor(rep(c("A",  "B", "C"), each=2))
df$par = rep(c("c1", "c2", "c3"), each=6)

g = ggplot(data =df, aes(y=est, x=m)) +
  geom_point() +
  geom_errorbarh(aes(xmax = m + 2*s, xmin = m-2*s), width=0.1) +
  facet_grid(data_set~par, scales="free_x") +
  xlab("Parameter value") + ylab("")
g

pdf("figure3.pdf", width=7.5, height=3.5)
print(g)
dev.off()

2 个答案:

答案 0 :(得分:6)

默认情况下,ggplot2使轴标题与轴文本非常接近。一个技巧是在字符串

中插入换行符\n
  xlab("\nParameter value") + ylab("")

output

答案 1 :(得分:4)

我认为这可能是pdf的问题。使用ggsavevjust = -0.5为我工作。我会用

替换代码的最后三行
ggsave('figure3.pdf', g + opts(axis.title.x = theme_text(vjust = -0.5)), 
   width = 7.5, height = 3.5)

这是输出。

enter image description here