为数据帧的两个子段创建单个图例

2024-04-23 12:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在不同的子地块上创建了一个带有两个轴的地块。当前一个覆盖另一个。问题是使图例包含堆栈中的两个标签。我该怎么做?你知道吗

d = data.groupby('atemp_rounded').sum().reset_index()
fig = plt.figure()
ax1 = fig.add_subplot(111) # don't know what 111 stands for...
ax2 = ax1.twinx()
d.plot(ax=ax1, y='casual')
d.plot(ax=ax2, y='registered', color='g')
plt.show()

bad legend


Tags: dataplot堆栈figplt标签axsum
1条回答
网友
1楼 · 发布于 2024-04-23 12:18:13

您可以将各个绘图的图例设置为关闭,而创建地物图例。要将其放置在轴边界内,需要在轴坐标中指定位置。你知道吗

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"A" : [3,2,1], "B" : [2,2,1]})

fig = plt.figure()
ax1 = fig.add_subplot(111) # don't know what 111 stands for...
ax2 = ax1.twinx()
df.plot(ax=ax1, y='A', legend=False)
df.plot(ax=ax2, y='B', color='g', legend=False)
fig.legend(loc="upper right", bbox_to_anchor=(0,0,1,1), bbox_transform=ax1.transAxes)
plt.show()

enter image description here

相关问题 更多 >