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

如何用ggplot2创建始于对应起始年、止于2022的横向条形图?

解决方案:创建从起始年份延伸至2022年的横向条形图

你的核心需求是展示各Type从起始年份到2022年的使用时长,原代码用geom_bar的方式无法实现,因为geom_bar默认从x=0开始绘制条形,长度对应映射的x值,和你的需求完全相反。以下是两种可行的实现方式:

方法1:使用geom_segment绘制水平条形

这种方式简单直接,通过线段模拟条形效果:

library(ggplot2)

table <- "startyear type
1  2007    AB
2  2007    BB
3  2010    CB
4  2020    AD
5  2015    BD
6  2022    CD"

df <- read.table(text=table, header = TRUE)

ggplot(df, aes(y = type)) +
  # 定义条形的起止年份,y轴保持对应Type的位置
  geom_segment(aes(x = startyear, xend = 2022, yend = type), 
               size = 8, # 调整条形粗细
               color = "#2c3e50") +
  # 自定义x轴刻度,让年份显示更清晰
  scale_x_continuous(breaks = seq(2007, 2022, 3)) +
  labs(x = "Year", y = "Type", title = "Type Usage Duration (2007-2022)") +
  theme_minimal()

方法2:使用geom_rect绘制填充式条形

如果需要带填充效果的标准条形,可以用矩形来实现:

ggplot(df, aes()) +
  # 定义每个矩形的起止范围:x从startyear到2022,y对应Type的位置区间
  geom_rect(aes(xmin = startyear, xmax = 2022, 
                ymin = as.numeric(type) - 0.4, ymax = as.numeric(type) + 0.4),
            fill = "#3498db", 
            alpha = 0.7) +
  # 将y轴刻度映射为Type名称
  scale_y_continuous(breaks = 1:nrow(df), labels = df$type) +
  scale_x_continuous(breaks = seq(2007, 2022, 3)) +
  labs(x = "Year", y = "Type", title = "Type Usage Duration (2007-2022)") +
  theme_minimal()

原代码问题说明

你之前的geom_bar(stat="identity")逻辑错误:

  • x = startyear是将条形长度设为起始年份的数值,而非条形的起始位置
  • geom_bar默认从x=0开始绘制,导致所有条形起点一致,完全不符合你“从起始年份延伸至2022”的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:24:17