【问题标题】:Plotting two data with greater difference绘制两个差异较大的数据
【发布时间】:2019-06-21 07:52:06
【问题描述】:
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不能很好地表示数据的直线。然而,只有var1var2,情节看起来不错。任何建议都是非常值得赞赏的。谢谢。

我主要使用plotly 来绘制数据,但我也可以使用matplotlib。

【问题讨论】:

  • 我赞成你的问题,因为它是mcve。感谢您的简洁和完整的提问

标签: python pandas matplotlib plot plotly


【解决方案1】:

只需使用第二个 y 轴,如下所示。首先创建一个轴对象ax,然后直接使用DataFrame 进行绘图,并将secondary_y=True 用于您的'sent' 列。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2017-07-11
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多