4
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  

Sample code

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()

Problem

I want to plot line chart using above three columns but the problem is that column sent has very small values as compared to other columns and when I add columns sent it's zoom out too much and the plot becomes nearly 3 straight lines that is not a good presentation of the data. However, with var1 and var2 only, plot is looking fine. Any suggestion would be highly appreciable. Thanks.

Primarily, I am using plotly to plot the data but I can also use matplotlib.

4

1 回答 1

4

Just use a secondary y axis as following. First create an axis object ax and then plot directly using the DataFrame and use secondary_y=True for your 'sent' column.

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')

enter image description here

Alternatively you can also use explicitly twinx as following which generates the below figure. This is a bit tricky because now you will have two separate legend boxes. If you want to merge the two boxes together, you can read this answer

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)

enter image description here

于 2019-01-28T10:26:01.360 回答