【问题标题】:How to get multiple legends from multiple pandas plots如何从多个熊猫图中获取多个图例
【发布时间】:2014-08-21 05:40:33
【问题描述】:

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

如果我用一列打开图例,它工作正常,但如果我尝试同时执行这两个操作,第二个会覆盖第一个。

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

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

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

【问题讨论】:

标签: python pandas ipython


【解决方案1】:

好的,感谢 unutbu 的评论指出我基本相同的问题(我搜索但没有找到),我只需要将我的 plot 命令修改为:

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

现在我得到了这个,这就是我想要的:

嗯。几乎。最好在图例上获得(右)和(左)以明确哪个比例适用于哪条线。 @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'))]);

产生:

【讨论】:

  • 实际上,我意识到这不是我想要的完全。我希望图例标题为 significant_wave_height (right),就像熊猫最初绘制它时一样。
  • ax.legend(lines, ['{} ({})'.format(l.get_label(), side) for l, side in zip(lines, ('left', 'right'))]) 会将(left)(right) 添加到标签中。
猜你喜欢
  • 2019-08-03
  • 2020-02-11
  • 1970-01-01
  • 2017-10-29
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
相关资源
最近更新 更多