You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中无需Rmarkdown将横竖方向绘图输出至同一PDF

嘿,这事儿好办!不用R Markdown也能轻松实现同一个PDF里混合横向和纵向的绘图,核心就是利用R的图形设备参数来切换页面方向,给你两种实用方案:

方案1:Base R 绘图实现混合方向

这种方法直接用Base R的绘图函数,通过调整页面尺寸来控制方向:

# 打开PDF设备,设置onefile=TRUE确保所有图都在同一个PDF里
pdf("mixed_plots.pdf", onefile = TRUE)

# 绘制第一个纵向图(默认页面尺寸就是纵向,也可以手动指定宽高)
par(mar = c(4, 4, 2, 1))  # 调整边距让图更美观
plot(1:20, main = "纵向折线图")

# 切换到横向页面:设置宽大于高
dev.new(width = 11, height = 8)
barplot(1:10, main = "横向柱状图")

# 切回纵向页面
dev.new(width = 8, height = 11)
hist(rnorm(100), main = "纵向直方图")

# 关闭PDF设备,完成输出
dev.off()
方案2:ggplot2 绘图实现混合方向

如果你用ggplot2画图,逻辑和Base R完全一致,只需要记得用print()输出图形:

library(ggplot2)

# 打开PDF设备
pdf("ggplot_mixed.pdf", onefile = TRUE)

# 纵向散点图
p1 <- ggplot(mtcars, aes(x = mpg, y = hp)) + 
  geom_point(color = "blue") + 
  ggtitle("纵向散点图")
print(p1)

# 切换到横向页面
dev.new(width = 11, height = 8)
# 横向箱线图
p2 <- ggplot(mtcars, aes(x = factor(cyl), y = disp)) + 
  geom_boxplot(fill = "lightgreen") + 
  ggtitle("横向箱线图")
print(p2)

# 切回纵向页面
dev.new(width = 8, height = 11)
# 纵向密度图
p3 <- ggplot(mtcars, aes(x = wt)) + 
  geom_density(fill = "orange", alpha = 0.5) + 
  ggtitle("纵向密度图")
print(p3)

# 关闭设备
dev.off()
几个实用小提示
  • 页面尺寸单位:dev.new()里的width和height默认是英寸,如果需要适配A4纸,纵向可以设width=8.27, height=11.69,横向就反过来width=11.69, height=8.27。
  • 每次绘制新图前一定要切换到对应尺寸的页面,不然会继承上一个页面的方向设置。
  • 如果想让所有页面的边距统一,可以在每个绘图前用par(mar = c(...))(Base R)或者theme(plot.margin = margin(...))(ggplot2)来调整。

内容的提问来源于stack exchange,提问作者user1769197

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:31:23