如何在R语言ggplot2中制作横轴为t-1/t-2/t-3的直方图
嘿,我懂你想要的那种图表!就是把t-3、t-2、t-1这些时间点作为横轴类别,对应展示各自的数值对吧?你现有的代码其实已经搭好基础了,只需要做几个小调整就能贴合你想要的效果:
制作目标时间点分组柱状图
首先,我们先过滤掉不需要的t类别,然后把横轴的时间点设置成你想要的顺序,再调整图表样式来匹配需求:
library(ggplot2) # 你的原始数据 df <- data.frame(trt = c("t-3", "t-2", "t-1", "t"), outcome = c(3, 6, 9, 5)) # 第一步:过滤出你需要的t-3、t-2、t-1三个时间点 target_df <- df[df$trt %in% c("t-3", "t-2", "t-1"), ] # 第二步:设置横轴顺序(避免默认字母排序打乱时间逻辑) target_df$trt <- factor(target_df$trt, levels = c("t-3", "t-2", "t-1")) # 第三步:绘制并美化图表 ggplot(target_df, aes(x = trt, y = outcome)) + geom_col(fill = "#2c3e50", width = 0.6) + # 调整柱子颜色和宽度,更接近示例图风格 labs( x = "时间点", y = "数值", title = "t-3/t-2/t-1 数值分布" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), axis.text = element_text(size = 10) )
额外优化:给柱子添加数值标签
如果你的示例图里柱子上方有具体数值,可以加上geom_text()来实现:
ggplot(target_df, aes(x = trt, y = outcome)) + geom_col(fill = "#2c3e50", width = 0.6) + geom_text(aes(label = outcome), vjust = -0.5, size = 4) + # 在柱子顶部显示数值 labs( x = "时间点", y = "数值", title = "t-3/t-2/t-1 数值分布" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), axis.text = element_text(size = 10) )
这样调整后,就能得到和你示例图风格一致、横轴为t-3/t-2/t-1的柱状图啦~
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

