如何从多个pandas图获取多个图例

2 投票
1 回答
1799 浏览
提问于 2025-04-18 11:37

我有两个数据框(都是按时间排序的),我想把这两个数据框中的列一起画在同一个图上,并且希望图例看起来就像这两个列在同一个数据框里一样。

如果我只打开一个列的图例,效果很好,但如果我尝试同时画两个列,第二个图例会把第一个图例覆盖掉。

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 个回答

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

撰写回答