【问题标题】:Create unique legend for subplot with different columns in pandas为熊猫中不同列的子图创建独特的图例
【发布时间】:2017-11-27 04:54:15
【问题描述】:

我必须从 2 个具有不同列的 df 中绘制 2 个子图。我想得到包含两者所有列的通用图例,类似于下面的示例。

d1 = pd.DataFrame({ #without one
    'two' : [-1.,- 2.,- 3., -4.],
    'three' : [4., 3., 2., 1.],
    'four' : [4., 3., 4., 3.]})
tot_1=d1.sum(axis=1)

d2 = pd.DataFrame({'one' : [1., 2., 3., 4.],
    'two' : [4., 3., 3., 1.],
    'three' : [-1., -1., -3., -4.],
    'four' : [4., 3., 2., 1.]})

tot_2=d2.sum(axis=1)


fig, ax = plt.subplots(nrows=2, ncols=1)

#plot 1
d1.plot.area(stacked=True,legend=False,ax=ax[0])
tot_1.plot(linestyle='-', color='black',legend=False,ax=ax[0])

###SECOND GRAPH####

ax3 = ax[1].twiny()

#plot 2
d2.plot.area(stacked=True,legend=False,ax=ax[1],sharex=ax[0])
tot_2.plot(linestyle='-',color='black',legend=False,ax=ax[1])

plt.show()

问题在于两个数据框/绘图中的列不完全相同(两者都不同),并且应确保图例具有两个绘图中的所有列和颜色并且图例匹配.

如果我可以为每列选择颜色,则更好(但不是必需),例如使用带有col_name:color 的字典来传递

【问题讨论】:

标签: python pandas matplotlib plot visualization


【解决方案1】:

您确实可以使用包含 column-name:color 对的字典来为补丁着色,然后从中创建一个图例。

import pandas as pd
import matplotlib.pyplot as plt

d1 = pd.DataFrame({ #without one
    'two' : [-1.,- 2.,- 3., -4.],
    'three' : [4., 3., 2., 1.],
    'four' : [4., 3., 4., 3.]})
tot_1=d1.sum(axis=1)

d2 = pd.DataFrame({'one' : [1., 2., 3., 4.],
    'two' : [4., 3., 3., 1.],
    'three' : [-1., -1., -3., -4.],
    'four' : [4., 3., 2., 1.]})
tot_2=d2.sum(axis=1)

columns = ["one", "two", "three", "four"]
colors = dict(zip(columns, ["C"+str(i) for i in range(len(columns)) ]))

fig, ax = plt.subplots(nrows=2, ncols=1)

#plot 1
d1.plot.area(stacked=True,legend=False,ax=ax[0], lw=0,
             color=[colors[i] for i in d1.columns])
tot_1.plot(linestyle='-', color='black',legend=False,ax=ax[0])

###SECOND GRAPH####

ax3 = ax[1].twiny()

#plot 2
d2.plot.area(stacked=True,legend=False,ax=ax[1],sharex=ax[0], lw=0,
             color=[colors[i] for i in d2.columns])
tot_2.plot(linestyle='-',color='black',legend=False,ax=ax[1])

labels = list(set(list(d1.columns) + list(d2.columns)))

handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
ax3.legend(handles=handles, labels=labels)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2018-11-30
    • 2018-09-16
    • 2020-04-02
    • 2015-04-04
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多