当转换为jpg格式时,ggplot2图像有太大的图例

时间:2017-01-13 02:35:40

标签: r plot

我正在制作一份提交给学术期刊的情节。 我使用png()函数进行消除锯齿,但是图中的图例太大了。

请参阅下面的示例代码和图表。

posn.d <- position_dodge(0.1)
plot_test <- ggplot(mtcars, aes(factor(gear), hp, shape = factor(am)))+
  ylab("HP")+
  stat_summary(fun.y = mean, geom = "point", position = posn.d, aes(shape = factor(am)), size = 1)+
  stat_summary(fun.y = mean, geom = "line", position = posn.d, aes(group = factor(am), linetype = factor(am)), size = 0.4)+
  stat_summary(fun.data = mean_se, fun.args = list(mult = 1), geom = "errorbar", width = 0.1, position =posn.d, size=0.3)+
  theme(legend.key = element_rect(colour = "white"), panel.border = element_blank(), panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
        axis.title.y=element_text(vjust=1,face="bold",size=6), axis.title.x = element_blank(),
        axis.text.x=element_text(size=6, face = "bold"), axis.text.y=element_text(size=6, face = "bold"),
        axis.line.x=element_line(size=0.2),axis.line.y=element_line(size=0.2),axis.ticks=element_line(size=0.2),
        plot.title=element_text(hjust=0,vjust=2,face="bold", size=3))+
  scale_linetype_manual(name = "AM", labels = c("am0", "am1"), values = c("solid", "dotted"))+
  scale_shape_manual(name = "AM", labels = c("am0", "am1"), values = c(16, 15))+
  scale_x_discrete(labels = c("three", "four", "five"))


png(width = 100, height = 35, units="mm", filename = "test.jpg", type = "cairo", antialias = "subpixel", family = "malgun", res = 300)
plot_test
dev.off()

enter image description here

我试图通过添加

来缩小图例标题和文字的大小
legend.title = element_text(size = 4, face = "bold"), legend.text = element_text(size = 4) 

在主题()中。 但是传说文本和标题之间的空间仍然太大,看起来很难控制。

有人可以帮助我而不改变整个图像大小或分辨率吗? (因为无法自由控制尺寸和分辨率以符合期刊的指导原则。)

1 个答案:

答案 0 :(得分:0)

您应该使用legend.key.size来调整图例显示的大小。您可以尝试以下代码。并使用legend.margin来控制在图例周围添加的额外空间。

plot_test <- plot_test + 
  theme(legend.key.size = unit(0.2, "cm"),
        legend.margin = unit(0, "cm")
        legend.title = element_text(size = 4, face = "bold"), 
        legend.text = element_text(size = 4))

png(width = 100, height = 35, units="mm", filename = "test.jpg", type = "cairo", antialias = "subpixel", family = "malgun", res = 300)
plot_test
dev.off()