python - 反转图例的顺序

标签 python matplotlib reverse legend

我使用下面的代码来绘制条形图,并且需要以相反的顺序呈现一个图例。我该怎么做?

colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
p = numpy.empty(len(C2), dtype=object)
plt.figure(figsize=(11, 11))

prevBar = 0
for index in range(len(C2)):
    plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index],
            label=C0[index])
    prevBar = prevBar + C2[index]

# Positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i + (width/2) for i in ind]

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# Set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0, 70000, 3000))
plt.legend(title="Line", loc='upper left')

# Set a buffer around the edge
plt.xlim(-width*2, width*2)
plt.show()

最佳答案

你可以打电话

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2016)

C0 = list('ABCDEF')
C2 = np.random.randint(20000, size=(len(C0), 3))
width = 1.0
C1 = ['foo', 'bar', 'baz']
ind = np.linspace(-width, width, len(C1))


colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
fig = plt.figure(figsize=(11,11))
ax = fig.add_subplot(1, 1, 1)

prevBar = 0
for height, color, label in zip(C2, colorsArr, C0):
    h = ax.bar(ind, height, width, bottom=prevBar, color=color, label=label)
    prevBar = prevBar + height

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(width/2.0) for i in ind]
# set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0,70000,3000))

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

plt.show()

enter image description here

关于python - 反转图例的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34576059/

相关文章:

python - Django:如何编写以下的反向函数

javascript - 如何使用 innerHTML 输出反向字符串?

python - SqlAlchemy:过滤以匹配列表中的所有值而不是任何值?

python - Django ifequal 和 if 语句总是转到 Else 标签

python - 如何使用 Selenium 获取动态 html?

python - 导入错误 : DLL load failed importing spacy

python - 用不同颜色绘制线

python - 如何反转字符串中单词的顺序

python - 使 pyplot.hist() 第一个和最后一个 bin 包含离群值

python - 如何使用 matplotlib scatter() 调整每个点的 alpha?