从循环构建图时显示独特的图例元素

时间:2019-03-04 16:35:47

标签: matplotlib

我正在尝试绘制间隔样式图,如下面的代码所示。我正在使用外观来实现这一目标。但是,当我尝试查看图例时,每个类别都绘制了多个图例元素。

如何绘制图例中只有一个元素的图,即仅显示A和B项?

谢谢。

import matplotlib.pyplot as plt
import pandas as pd

data = pd.DataFrame({'code':['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                     'd1':[1,2,3,4,5,1,2,3,4,5],
                     'd2':[2,3,4,5,6,2,3,4,5,6]})

f, ax = plt.subplots(1,1)
for lab, col in zip(['A', 'B'], ['red', 'green']):
    _ = data[data['code'] == lab]
    ax.plot((_['code'].values[0], _['code'].values[0]), (_['d1'], _['d2']),
            label = lab, color = col)
ax.legend()

2 个答案:

答案 0 :(得分:1)

您快到了。您已经正确提取了绘图的x值,但是,您忘记了对y值执行相同的操作。因此,您正在为每个y值创建一个图例条目。

您可能不希望在调用(_['d1'], _['d2'])时使用ax.plot,例如(_['d1'].values.min(), _['d2'].values.max())

import matplotlib.pyplot as plt
import pandas as pd

data = pd.DataFrame({'code':['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                     'd1':[1,2,3,4,5,1,2,3,4,5],
                     'd2':[2,3,4,5,6,2,3,4,5,6]})

f, ax = plt.subplots(1,1)

for lab, col in zip(['A', 'B'], ['red', 'green']):
    _ = data[data['code'] == lab]
    ax.plot((_['code'].values[0], _['code'].values[0]), (_['d1'].values[0], _['d2'].values[-1]),
            label = lab, color = col)
ax.legend()

enter image description here

答案 1 :(得分:0)

替代解决方案可能看起来像

from collections import OrderedDict

# rest of the code

for lab, col in zip(['A', 'B'], ['red', 'green']):
    _ = data[data['code'] == lab]
    ax.plot((_['code'].values[0], _['code'].values[0]), (_['d1'], _['d2']),
            label = lab , color = col)
    i +=1 
ax.legend()

handles, labels = ax.get_legend_handles_labels()
unique = OrderedDict(zip(labels, handles))
ax.legend(unique.values(), unique.keys())

enter image description here