I have this data frame:
import pandas as pd
In:
df= pd.DataFrame({'Date':['2007-01-01 07:14:00','2007-01-01
07:25:00','2007-01-01 08:00:00','2007-01-01 09:14:00','2007-01-01
09:33:12'],'sent':[-0.32,0.34,-0.45,0.7,0.22],'var1':
[114,115,111,112,113],
'var2':[110,111,115,112,109]})
print(df)
_____________________________________
out:
Date sent var1 var2
0 2007-01-01 07:14:00 -0.32 114 110
1 2007-01-01 07:25:00 0.34 115 111
2 2007-01-01 08:00:00 -0.45 111 115
3 2007-01-01 09:14:00 0.70 112 112
4 2007-01-01 09:33:12 0.22 113 109
示例代码
import matplotlib.pyplot as plt
plt.plot(df.Date,df.sent,label='sent')
plt.plot(df.Date,df.var1,label='price1')
plt.plot(df.Date,df.var2,label= 'price2')
plt.show()
问题
我想使用以上三列绘制折线图,但问题是 sent
列与其他列相比具有非常小的值,当我添加 sent
列时,它是缩小太多,绘图变成近 3 条直线,这不是数据的良好呈现。然而,只有 var1
和 var2
, plotly 看起来很好。任何建议将不胜感激。谢谢。
我主要使用 plotly
来绘制数据,但我也可以使用 matplotlib。
最佳答案
只需使用辅助 y 轴,如下所示。首先创建一个轴对象 ax
,然后使用 DataFrame 直接绘制,并为您的 'sent'
列使用 secondary_y=True
。
import matplotlib.pyplot as plt
df= pd.DataFrame({'Date':['2007-01-01 07:14:00','2007-01-01 07:25:00','2007-01-01 08:00:00',
'2007-01-01 09:14:00','2007-01-01 09:33:12'],
'sent':[-0.32,0.34,-0.45,0.7,0.22],'var1': [114,115,111,112,113],
'var2':[110,111,115,112,109]})
fig, ax = plt.subplots()
df.plot('Date','var1',label='price1', ax=ax)
df.plot('Date','var2',label= 'price2',ax=ax)
df.plot('Date','sent',secondary_y=True, ax=ax, label='sent')
或者您也可以显式使用 twinx
如下生成下图。这有点棘手,因为现在您将有两个单独的图例框。如果想把两个框合并在一起,可以看this回答
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(df.Date,df.var1,label='price1')
ax.plot(df.Date,df.var2,label= 'price2')
ax.legend(loc=0)
ax1 = ax.twinx()
ax1.plot(df.Date,df.sent,color='g', label='sent')
ax1.legend(loc=2)
关于python - 绘制差异较大的两个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54399827/