首页 > 解决方案 > 如何在 matplotlib 中绘制垂直条

问题描述

我想在具有其他时间序列的图上显示 0 或 1 数组的值。

我怎样才能实现像下面的灰线一样的东西 - 除了我的会摆动得更多。

在此处输入图像描述系列。

例如,如何在此处添加 osc:

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

n = 100
x = range(n)
y = np.random.rand(100)
osc = np.random.randint(2, size=n)

plt.plot(x,y)
plt.show(block=True)

标签: python-3.xmatplotlib

解决方案


好吧,您可以遍历这些值并调用axvspan(x0,x1,color=...,alpha=...);

import numpy as np
import matplotlib.pyplot as plt

n = 100
x = range(n)
y = np.random.randn(100).cumsum()
osc = np.random.randint(2, size=n)

plt.plot(x, y, color='crimson')
for x0, x1, os in zip(x[:-1], x[1:], osc):
    if os:
        plt.axvspan(x0, x1, color='blue', alpha=0.2, lw=0)
plt.margins(x=0)
plt.show()

请注意,仅使用前 99 个值osc,因为只有 99 个区间。

循环中的 axvspan


推荐阅读