我有一个可变比例数据的数据框,我试图得到一个带有子图的图。像这样的。
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()
以及输出
脚本的主要问题是生成3个轴,但只在其中一个轴上打印,需要将每个轴视为一个单独的对象,具有自己的y比例、y限制等。例如,在您的脚本中,当您调用
fig, ax = plt.subplots()
时,您将生成第一个称为ax的轴(这是标度在绘图左侧的标准yaxis)。如果你想在这个轴上绘制一些东西,你应该调用ax.plot()
,但是在你的例子中,你正在绘制所有你称之为mm的轴上的东西。 我认为您应该仔细阅读matplotlib文档,以便更好地理解这些概念。对于在多个y轴上绘图,我建议您看看这个example。你知道吗下面是一个将数据绘制在3个不同y轴上的基本示例,您可以将其作为生成所需图形的起点。你知道吗
结果如下:
p.s.您的示例数据帧包含不存在的日期(2020年2月31日),因此您必须修改这些日期才能将索引转换为日期时间。你知道吗
相关问题 更多 >
编程相关推荐