Reverse the order of a 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()
这篇关于颠倒图例的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:颠倒图例的顺序
基础教程推荐
猜你喜欢
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01