【发布时间】:2019-11-14 12:38:13
【问题描述】:
受answer given here 的启发,我希望展示一个非常相似的图,每条线的开始日期位于左侧 y 轴,结束日期位于右侧 y 轴。
到目前为止,我尝试将开始日期和结束日期都保存在一个列表中,并使用了twinx() 和set_yticks(),但这不起作用。下面的代码在链接中绘制了相同的图(除了图例),但它不会修改 y 轴。
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from datetime import datetime
ts = pd.date_range(end='2016-03-31', periods=250, freq='D')
np.random.seed([3, 1415])
a = np.random.choice(range(100), size=(2,10))
ranges = pd.DataFrame((a + np.array([[0], [150]])), columns=list('abcdefghij'))
df = pd.DataFrame(index=ts)
count = len(ranges.columns)
left_axis = []
right_axis = []
for colname, column in ranges.iteritems():
start_, end_ = column
df.loc[ts[start_] : ts[end_], colname] = count
left_axis.append(ts[start_])
right_axis.append(ts[end_])
count -= 1
fig, ax1 = plt.subplots()
ax1.plot(df)
ax1.set_yticks(range(10, 0, -1), left_axis)
ax2 = ax1.twinx()
ax2.set_yticks(range(10, 0, -1), right_axis)
plt.legend([])
plt.show()
任何帮助将不胜感激。非常感谢您!
【问题讨论】:
标签: python matplotlib timestamp yaxis