如何从多个熊猫图中获取多个图例

时间:2014-06-30 19:01:13

标签: python pandas ipython

我有两个数据帧(都是按时编制索引),我想在同一个图上将两个数据帧的列绘制在一起,图例就像在同一个数据帧中有两列一样。

如果我用一列启用图例,它可以正常工作,但如果我尝试两者都行,第二个会覆盖第一个。

import pandas as pd

# Use ERDDAP's built-in relative time functionality to get last 48 hours:
start='now-7days'
stop='now'

# URL for wind data
url='http://www.neracoos.org/erddap/tabledap/E01_met_all.csv?\
station,time,air_temperature,barometric_pressure,wind_gust,wind_speed,\
wind_direction,visibility\
&time>=%s&time<=%s' % (start,stop)

# load CSV data into Pandas
df_met = pd.read_csv(url,index_col='time',parse_dates=True,skiprows=[1])  # skip the units row 

# URL for wave data
url='http://www.neracoos.org/erddap/tabledap/E01_accelerometer_all.csv?\
station,time,mooring_site_desc,significant_wave_height,dominant_wave_period&\
time>=%s&time<=%s' % (start,stop)

# Load the CSV data into Pandas
df_wave = pd.read_csv(url,index_col='time',parse_dates=True,skiprows=[1])  # skip the units row 

绘制一个正常工作:

df_met['wind_speed'].plot(figsize=(12,4),legend=True);

enter image description here

但如果我尝试绘制两者,第一个图例就会消失:

df_met['wind_speed'].plot(figsize=(12,4),legend=True)
df_wave['significant_wave_height'].plot(secondary_y=True,legend=True);

enter image description here

1 个答案:

答案 0 :(得分:3)

好的,感谢unutbu的评论指向基本上相同的问题(我搜索但未找到),我只需要将我的情节命令修改为:

df_met['wind_speed'].plot(figsize=(12,4))
df_wave['significant_wave_height'].plot(secondary_y=True);
ax = gca();
lines = ax.left_ax.get_lines() + ax.right_ax.get_lines()
ax.legend(lines, [l.get_label() for l in lines])

现在我得到了这个,这就是我想要的: enter image description here

好。几乎。得到图例上的(右)和(左)会很清楚哪个比例是哪一行。 @unutbu再次救援:

df_met['wind_speed'].plot(figsize=(12,4))
df_wave['significant_wave_height'].plot(secondary_y=True);
ax = gca();
lines = ax.left_ax.get_lines() + ax.right_ax.get_lines()
ax.legend(lines, ['{} ({})'.format(l.get_label(), side) for l, side in zip(lines, ('left', 'right'))]);

产生

enter image description here