在子图的同一y轴上绘制不同比例的数据

2024-05-08 21:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个可变比例数据的数据框,我试图得到一个带有子图的图。像这样的。enter image description here

raw_data = {'strike_date': ['2019-10-31', '2019-11-31','2019-12-31','2020-01-31', '2020-02-31'], 
            'strike': [100.00, 113.00, 125.00, 126.00, 135.00], 
            'lastPrice': [42, 32, 36, 18, 23], 
            'volume': [4, 24, 31, 2, 3],
            'openInterest': [166, 0, 0, 62, 12]}
    ploty_df = pd.DataFrame(raw_data, columns = ['strike_date', 'strike', 'lastPrice', 'volume', 'openInterest'])
    ploty_df





strike_date strike  lastPrice   volume  openInterest
0   2019-10-31  100.0   42  4   166
1   2019-11-31  113.0   32  24  0
2   2019-12-31  125.0   36  31  0
3   2020-01-31  126.0   18  2   62
4   2020-02-31  135.0   23  3   12

这是我用twinx试过的,如果你注意到输出是一个平坦的数据,没有任何冲击和体积的尺度差异。你知道吗

    fig, ax = plt.subplots()
fig.subplots_adjust(right=0.75)

mm = ax.twinx()
yy = ax.twinx()
for col in ploty_df.columns:
        mm.plot(ploty_df.index,ploty_df[[col]],label=col)
mm.set_ylabel('volume')
yy.set_ylabel('strike')
yy.spines["right"].set_position(("axes", 1.2))
yy.set_ylim(mm.get_ylim()[0]*12, mm.get_ylim()[1]*12)
plt.tick_params(axis='both', which='major', labelsize=16)

handles, labels = mm.get_legend_handles_labels()
mm.legend(fontsize=14, loc=6)
plt.show()

以及输出

enter image description here


Tags: 数据dfdatepltcolaxmmset
1条回答
网友
1楼 · 发布于 2024-05-08 21:11:36

脚本的主要问题是生成3个轴,但只在其中一个轴上打印,需要将每个轴视为一个单独的对象,具有自己的y比例、y限制等。例如,在您的脚本中,当您调用fig, ax = plt.subplots()时,您将生成第一个称为ax的轴(这是标度在绘图左侧的标准yaxis)。如果你想在这个轴上绘制一些东西,你应该调用ax.plot(),但是在你的例子中,你正在绘制所有你称之为mm的轴上的东西。 我认为您应该仔细阅读matplotlib文档,以便更好地理解这些概念。对于在多个y轴上绘图,我建议您看看这个example。你知道吗

下面是一个将数据绘制在3个不同y轴上的基本示例,您可以将其作为生成所需图形的起点。你知道吗

#convert the index of your dataframe to datetime
plot_df.index=pd.DatetimeIndex(plot_df.strike_date)

fig, ax = plt.subplots(figsize=(15,7))
fig.subplots_adjust(right=0.75)

l1,=ax.plot(plot_df['strike'],'r')
ax.set_ylabel('Stike')

ax2=ax.twinx()
l2,=ax2.plot(plot_df['lastPrice'],'g')
ax2.set_ylabel('lastPrice')

ax3=ax.twinx()
l3,=ax3.plot(plot_df['volume'],'b')
ax3.set_ylabel('volume')
ax3.spines["right"].set_position(("axes", 1.2))
ax3.spines["right"].set_visible(True)

ax.legend((l1,l2,l3),('Stike','lastPrice','volume'),loc='center left')

结果如下: enter image description here

p.s.您的示例数据帧包含不存在的日期(2020年2月31日),因此您必须修改这些日期才能将索引转换为日期时间。你知道吗

相关问题 更多 >