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

如何用R语言绘制带下方观测数表格的折线图?

折线图下方添加观测数表格的实现方案

你可以通过调整现有代码的表格样式、对齐方式,让折线图和下方的观测数表格更贴合示例效果,以下是优化后的实现代码:

library(ggplot2)
library(gridExtra)
library(tidyr)

# 生成示例数据
set.seed(123)
df <- data.frame(
  time = 1:10,
  group1_value = cumsum(rnorm(10)),
  group2_value = cumsum(rnorm(10)),
  group1_count = sample(20:50, 10, replace = TRUE),
  group2_count = sample(20:50, 10, replace = TRUE)
)

# 重塑数据用于绘图
df_long <- pivot_longer(df, cols = c(group1_value, group2_value),
                        names_to = "group", values_to = "value")

# 创建折线图,调整底部边距并隐藏x轴标签(表格会显示时间)
plot <- ggplot(df_long, aes(x = time, y = value, color = group)) +
  geom_line(linewidth = 1) +
  labs(title = "Group 1 and Group 2", x = "", y = "Value") +
  theme(
    plot.margin = unit(c(1, 1, 0, 1), "lines"),  # 调整底部边距,让表格和图紧密衔接
    axis.text.x = element_blank(),  # 隐藏图的x轴刻度文字,用表格显示时间
    axis.ticks.x = element_blank()
  )

# 准备表格数据
table_data <- data.frame(
  Time = df$time,
  Group1 = df$group1_count,
  Group2 = df$group2_count
)

# 创建表格对象,优化样式
table_grob <- tableGrob(
  table_data,
  rows = NULL,  # 去掉表格的行名
  theme = ttheme_minimal(
    core = list(
      padding = unit(c(3, 3), "mm"),
      fg_params = list(fontsize = 10)
    ),
    colhead = list(
      fg_params = list(fontface = "bold", fontsize = 10)
    )
  )
)

# 让表格宽度和折线图匹配
table_grob$widths <- plot$theme$axis.text.x$width %||% unit(rep(1, ncol(table_data)), "null")

# 组合图和表格
grid.arrange(
  plot, table_grob,
  ncol = 1,
  heights = c(4, 1)  # 调整图和表格的高度比例
)

关键调整说明:

  • 隐藏了折线图的x轴刻度和标签,避免和表格的时间列重复,让整体更简洁
  • 优化了表格的主题样式,设置表头加粗、调整内边距,提升可读性
  • 调整了图和表格的高度比例,让可视化更协调
  • 确保表格宽度和折线图匹配,避免左右错位

如果想要更便捷的布局控制,也可以使用patchwork包替代gridExtra,代码如下:

library(patchwork)

# 组合图和表格,使用patchwork的布局
plot / table_grob +
  plot_layout(heights = c(4, 1)) +
  plot_annotation(title = "Group 1 and Group 2")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:15:26