You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在绘图中添加两条竖线并填充区域以高亮特定时段?

嘿,这个需求太普遍了!不管你是用Python的Matplotlib还是R的ggplot2,都能快速搞定。我给你准备了两个常用工具的实操代码,直接改参数就能适配你的数据~

在Python Matplotlib中实现

如果你用Matplotlib画时间序列或者普通折线图,用axvline画竖线,fill_between填充区域就可以。这里给你一个完整的时间序列例子:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 生成模拟时间序列数据
dates = pd.date_range(start='2024-01-01', end='2024-01-31')
values = np.random.randn(len(dates)).cumsum()

# 创建绘图对象
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(dates, values, label='每日数据')

# 定义要高亮的时段
highlight_start = pd.to_datetime('2024-01-10')
highlight_end = pd.to_datetime('2024-01-20')

# 添加两条红色虚线竖线
ax.axvline(x=highlight_start, color='red', linestyle='--', linewidth=2)
ax.axvline(x=highlight_end, color='red', linestyle='--', linewidth=2)

# 填充竖线之间的区域
ax.fill_between(
    x=dates,
    y1=ax.get_ylim()[0],  # 自动获取y轴最小值
    y2=ax.get_ylim()[1],  # 自动获取y轴最大值
    where=(dates >= highlight_start) & (dates <= highlight_end),
    color='orange',
    alpha=0.3,  # 设透明度避免遮挡数据
    label='高亮时段'
)

# 美化图表
ax.set_xlabel('日期')
ax.set_ylabel('累计值')
ax.set_title('高亮特定时段的时间序列图')
ax.legend()
plt.xticks(rotation=45)
plt.tight_layout()

plt.show()

关键细节

  • axvline可以自定义颜色、线型和线宽,适配你的图表风格
  • fill_betweenwhere参数精准控制填充范围,不用手动计算坐标
  • alpha参数一定要调,0.2-0.4的透明度既能突出高亮,又不会盖住数据
在R ggplot2中实现

用ggplot2的话,geom_vline画竖线,annotate("rect")来填充区域。注意图层顺序——填充区域要放在数据图层下面,不然会挡住折线:

library(ggplot2)
library(lubridate)

# 模拟数据
dates <- seq(as.Date("2024-01-01"), as.Date("2024-01-31"), by = "day")
values <- cumsum(rnorm(length(dates)))
df <- data.frame(date = dates, value = values)

# 定义高亮时段
highlight_start <- ymd("2024-01-10")
highlight_end <- ymd("2024-01-20")

# 绘图
ggplot(df, aes(x = date, y = value)) +
  # 先画填充区域(底层)
  annotate(
    "rect",
    xmin = highlight_start,
    xmax = highlight_end,
    ymin = -Inf,  # 自动延伸到y轴底部
    ymax = Inf,   # 自动延伸到y轴顶部
    fill = "orange",
    alpha = 0.3
  ) +
  # 再画数据折线
  geom_line(color = "blue", linewidth = 1) +
  # 添加两条红色虚线竖线
  geom_vline(xintercept = highlight_start, color = "red", linetype = "dashed", linewidth = 1) +
  geom_vline(xintercept = highlight_end, color = "red", linetype = "dashed", linewidth = 1) +
  # 美化设置
  labs(x = "日期", y = "累计值", title = "用ggplot2高亮特定时段") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

小技巧

  • 如果不是时间轴,把xmin/xmax换成数值就行,比如xmin=5, xmax=10
  • 要高亮多个时段?多写几个annotategeom_vline就行
  • 可以调整fill的颜色,比如用"#FFCC80"这种十六进制色号,更贴合你的图表主题

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

火山引擎 最新活动