我需要一个在折线图下包含观测数量的表,如下例所示: (https://i.stack.imgur.com/5R01E.png)

如有任何帮助,我们将不胜感激.

这就是我到目前为止try 过的:

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

# Example data
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)
)

# Reshape data for easier plotting
df_long <- pivot_longer(df, cols = c(group1_value, group2_value),
                        names_to = "group", values_to = "value")

# Create the plot
plot <- ggplot(df_long, aes(x = time, y = value, color = group)) +
  geom_line() +
  labs(title = "Group 1 and Group 2") +
  theme(plot.margin = unit(c(0, 0, 1, 0), "lines"))  # Adjust bottom margin to leave space for the table

# Create a data frame for the table
table_data <- data.frame(
  Time = df$time,
  Group1 = df$group1_count,
  Group2 = df$group2_count
)

# Create the table
table_grob <- tableGrob(table_data)

# Adjust table appearance
table_grob$widths <- unit(rep(1, ncol(table_data)), "null")
table_grob$heights <- unit(rep(1, nrow(table_data) + 1), "null")
table_grob$vp <- NULL

# Arrange plot and table
grid.arrange(
  plot, table_grob,
  ncol = 1,
  heights = c(3, 1)  # Adjust the relative heights of the plot and table
)

推荐答案

这里有一种不同的方法,它使用ggplot2创建表格,并使用patchwork将绘图和表格粘合在一起.

注意:我稍微简化了整形,以便一次性获得一个值和一个计数列.

library(ggplot2)
library(tidyr)
library(patchwork)

df_long <- pivot_longer(df,
  cols = starts_with("group"),
  names_to = c("group", ".value"),
  names_sep = "_"
)

plot <- ggplot(df_long, aes(x = time, y = value, color = group)) +
  geom_line() +
  labs(title = "Group 1 and Group 2")

table <- ggplot(df_long) +
  geom_text(aes(
    x = time, y = group, label = count
  ), size = .8 * 11 / .pt) +
  scale_x_continuous(
    breaks = scales::breaks_width(1),
    position = "top"
  ) +
  theme_light() +
  theme(
    text = element_text(color = "black"),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    panel.border = element_blank()
  ) +
  labs(y = NULL, x = NULL, title = "My table title")

plot / table +
  plot_layout(axes = "collect", heights = c(3, 1))

R相关问答推荐

给定R中另一行中的值,如何插补缺失值

使用rlang s arg_match判断函数输入列表

具有多个依赖变量/LHS的逻辑模型

更新合适的R mgcv::bam模型报告无效类型(关闭).'';错误

如何在xyplot中 for each 面板打印R^2

如何动态更新selectizeInput?

在R中使用数据集名称

当我们有多个特殊字符时,使用gsub删除名称和代码'

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

将饼图插入条形图

如何在ggplot2中绘制具有特定 colored颜色 的连续色轮

如何在R中使用hmm TMB提前一步预测观察到的状态?

Geom_arcbar()中出错:找不到函数";geom_arcbar";

防止在更新SHINY中的Reactive Value的部分内容时触发依赖事件

`-`是否也用于数据帧,有时使用引用调用?

将仪表板中的值框大小更改为Quarto

从矩阵创建系数图

子样本间系数检验的比较

无法保存gglot的所有pdf元素

在直方图中显示两个变量