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

Base R中如何将日度数据适配到月度图并添加底部状态条

Base R 实现底部日度粒度财务状态指示条

实现思路

无需对日度数据做月度聚合,直接通过矩形绘图函数逐天绘制对应颜色的色块,拼接为连续指示条即可100%保留日度数据精度,核心步骤如下:

  • 调整绘图区y轴范围,在0值下方预留指示条展示空间,避免遮挡原有利率折线
  • 按照给定的指数区间规则,给每日的指数值匹配对应显示颜色
  • 逐天绘制固定高度的彩色矩形,拼接为横跨整个x轴的连续指示条
  • 可选添加状态图例、自定义轴标签提升可读性

完整可运行代码

# ---------------------- 1. 测试数据生成(和你给出的数据结构完全对齐) ----------------------
set.seed(123)
# 2020、2021年月度利率数据
total2020Plot <- data.frame(
  Rates = c(26.17,20.55,23.21,20.55,19.55,17.30,18.10,17.72,16.47,17.71,17.52,19.76)
)
averagePlot <- data.frame(
  Rates = total2020Plot$Rates + rnorm(12, 0, 2)
)
# 日度财务指数数据
dates <- seq(as.Date("2020/01/01"), by = "day", length.out = 366)
daily_index <- runif(366, min=0, max=100)
daily_df <- data.frame(date = dates, index = daily_index)

# ---------------------- 2. 颜色映射规则(严格匹配区间要求) ----------------------
index_breaks <- c(-Inf, 20, 50, 70, 100)
index_cols <- c(
  "负债(0≤X<20)" = "red",
  "较差(20≤X<50)" = "orange",
  "良好(50≤X<70)" = "yellow",
  "优秀(70≤X<100)" = "forestgreen"
)
daily_df$col <- as.character(cut(
  daily_df$index,
  breaks = index_breaks,
  labels = index_cols
))

# ---------------------- 3. 绘图 ----------------------
# 月度折线点对应到日度x轴的月中位置,保证和底部日度条对齐
month_x_pos <- seq(15, 365, by = 30.5)
bar_height <- 3 # 指示条高度,可自行调整
plot(
  x = month_x_pos,
  y = total2020Plot$Rates,
  type = "l",
  col = 3, # 2020年曲线绿色
  ylim = c(-4, 35), # 下调y轴下限给指示条留空间
  xlim = c(1, 366),
  xaxt = "n",
  ylab = "利率",
  xlab = "月份",
  lwd = 2
)
lines(
  x = month_x_pos,
  y = averagePlot$Rates,
  type = "l",
  lty=2,
  col = 2, # 2021年曲线红色虚线
  lwd =2
)
grid()
abline(h=0, col = "gray30") # 绘制0值基准线

# 绘制底部日度指示条:每天对应1个单位宽度的矩形,无边框保证条带连续
n_days <- nrow(daily_df)
rect(
  xleft = 1:n_days - 0.5,
  xright = 1:n_days + 0.5,
  ybottom = 0 - bar_height,
  ytop = 0,
  col = daily_df$col,
  border = NA
)

# 可选:添加x轴月份刻度
axis(1, at = month_x_pos, labels = month.abb[1:12])
# 可选:添加财务状态图例
legend(
  "topright",
  legend = names(index_cols),
  fill = index_cols,
  cex = 0.8,
  title = "财务状态"
)

调整说明

  • 可通过修改bar_height参数、ylim下限值自由调整指示条的高度和上下位置
  • 如果你的x轴直接使用Date类坐标而非位置序号,只需把rect函数的xleft、xright参数替换为对应日期前后偏移0.5天即可,逻辑完全一致
  • 不需要对日度数据做任何聚合处理,每个色块对应单日数据,完全保留原始精度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:18:31