![](/img/trans.png)
[英]How to perform custom sort for both x- and y-axes on indexed DataFrame for heatmap?
[英]Set custom date ytick labels in both y-axes
受此處給出的答案的啟發,我希望顯示一個非常相似的圖,每條線的起始日期位於左側 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()
任何幫助將不勝感激。 非常感謝您提前!
你需要使用
ax.set_yticks(ticks)
ax.set_yticklabels(labels)
此外,為了確保右側的刻度與左側的刻度匹配,您必須調整ylim
使它們在兩個軸上都相同
(...)
fig, ax1 = plt.subplots()
ax1.plot(df)
ax1.set_yticks(range(10, 0, -1))
ax1.set_yticklabels(left_axis)
ax2 = ax1.twinx()
ax2.set_yticks(range(10, 0, -1))
ax2.set_yticklabels(right_axis)
ax2.set_ylim(ax1.get_ylim())
plt.legend([])
fig.tight_layout()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.