iPython笔记本 - 在subplot辅助y轴上设置ylim

时间:2015-01-22 18:13:02

标签: python matplotlib plot anaconda

我是Python的新手,我在iPython笔记本中工作。

我想使用辅助轴绘制子图中的数据。我可以设置ylim但它只影响辅助y轴(在右侧)。我无法找到控制主y轴(左侧)的ylim的方法。我希望主y轴的极限为[0,40],次y轴的极限值为[0,100]。


#import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import csv
import string
%pylab inline
%matplotlib inline

# READ IN FIRST CSV
espr = pd.read_csv('out.csv')
df_e = pd.DataFrame(espr)

#READ IN SECOND CSV
heat = pd.read_csv('heat.csv',encoding='ISO-8859-1',low_memory=False)
heat = heat[2:]
df_h = pd.DataFrame(heat,dtype='float64')
df_h = df_h.reset_index(drop=True)

#READ IN THIRD CSV
temp = pd.read_csv('temp.csv',encoding='ISO-8859-1',low_memory=False)
temp = temp[2:]
df_t = pd.DataFrame(temp,dtype='float64')
df_t = df_t.reset_index(drop=True)

# CONCATENATE DATAFRAMES
df_e = df_e[[' building:time step (-)', ' building:zone 01:air point:temperature (oC)', ' building:zone 05:air point:temperature (oC)']]
df_h = df_h[['TIME', 'Tdb_amb']]
df_t = df_t[['Tavg_diurn', 'Tavg_seas']]
sim = pd.concat([df_h, df_t, df_e],axis=1)

# SEPARATE DATA FOR PLOTTING
mar = sim[14160:21600]

这就是我跑到墙上的地方,我已经读过设置twinx()来设置不同轴的属性但是每当我尝试实现它时,它告诉我它没有知道什么是双胞胎。

fig, axes = plt.subplots(nrows=2, ncols=1)
fig.set_figheight(25)
fig.set_figwidth(20)

mar[' building:zone 01:air point:temperature (oC)'].plot(ax=axes[0])
mar[' building:zone 05:air point:temperature (oC)'].plot(ax=axes[0])
mar['Tavg_diurn'].plot(secondary_y=True, ax=axes[0])
mar['Tavg_seas'].plot(secondary_y=True, ax=axes[0])
ylim([0,100])

fig.tight_layout()

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:6)

如果axes是两个轴的数组,那么你可以这样做:

axes[0].set_ylim(0, 40)
axes[1].set_ylim(0, 100)

或使用pyplot's twinx()您可以尝试:

axes[0] = ax2.twinx()
axes[0].set_ylim(0, 40)
ax2.set_ylim(0, 100)

答案 1 :(得分:4)

关键是:axes[0].right_ax.set_ylim(0,100)

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline

fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(20, 10), sharex=True)

columns = [' building:zone 01:air point:temperature (oC)', ' building:zone 05:air point:temperature (oC)',
           'Tavg_diurn', 'Tavg_seas']
mar = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2010', periods=1000), columns=columns)
mar = mar.cumsum()
mar.plot(ax=axes[0], secondary_y=['Tavg_diurn', 'Tavg_seas'])
axes[0].set_ylim(0,40)
axes[0].right_ax.set_ylim(0,100)

A matplotlib figure resulting form the above code