我需要一个在折线图下包含观测数量的表,如下例所示: (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
)