R语言中如何调整ggplot图表尺寸?尝试theme参数报错求助
正确调整ggplot图表尺寸的方法
你用theme()设置figure.width或plot.width的方式不对,这两个参数不属于ggplot的主题配置项,所以会触发错误。下面是几种靠谱的调整方法:
方法1:保存图表时用ggsave()指定尺寸(推荐)
ggplot生成的是图形对象,在保存时精准设置宽高是最灵活的方式,默认单位为英寸:
# 先定义图表对象 accident_plot <- ggplot(accident_day, aes(year, accidents, group = 1)) + geom_point() + geom_line() + labs(title = "THE RATE OF ACCIDENTS", x = "Year", y = "Number of Accidents") # 保存时设置尺寸与分辨率 ggsave("accidents_trend.png", plot = accident_plot, width = 8, height = 4, dpi = 300)
方法2:通过图形设备设置尺寸(脚本/R Markdown场景)
- 普通R脚本:先打开对应格式的图形设备并指定尺寸,再绘制图表:
# 打开PNG设备,设置宽8英寸、高4英寸,分辨率300dpi png("accidents_trend.png", width = 8, height = 4, units = "in", res = 300) ggplot(accident_day, aes(year, accidents, group = 1)) + geom_point() + geom_line() + labs(title = "THE RATE OF ACCIDENTS", x = "Year", y = "Number of Accidents") dev.off() # 关闭设备,完成输出
- R Markdown:直接在代码块选项中设置:
```{r, fig.width=8, fig.height=4} ggplot(accident_day, aes(year, accidents, group = 1)) + geom_point() + geom_line() + labs(title = "THE RATE OF ACCIDENTS", x = "Year", y = "Number of Accidents")
## 方法3:全局设置默认图表尺寸(不推荐,影响所有图表) 如果需要临时让所有后续ggplot图表都使用统一尺寸,可以通过`options()`配置: ```r # 设置默认宽8英寸、高4英寸 options(repr.plot.width = 8, repr.plot.height = 4) # 之后绘制的图表都会应用这个尺寸 ggplot(accident_day, aes(year, accidents, group = 1)) + geom_point() + geom_line() + labs(title = "THE RATE OF ACCIDENTS", x = "Year", y = "Number of Accidents")
内容的提问来源于stack exchange,提问作者diorzyon
相关产品推荐
相关产品推荐

