python - 如何在不排序条形的情况下可视化水平条形图?
问题描述
我想绘制一个水平条形图,我这样做:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def plot_results(title, freq, labels):
# create the figure
matplotlib.rcParams.update({'font.size': 15})
fig, ax1 = plt.subplots(figsize=(9, 4))
fig.subplots_adjust(left=0.115, right=0.88)
pos = np.arange(len(labels))
rects = ax1.barh(pos, freq, align='center', height=0.8, tick_label = labels)
ax1.set_title(title)
ax1.set_xlim([0, 1])
ax1.xaxis.set_major_locator(MaxNLocator(11))
ax1.xaxis.grid(True, linestyle='--', which='major', color='grey', alpha=.25)
rect_labels = []
# Lastly, write in the ranking inside each bar to aid in interpretation
for i in range(0, len(rects)):
# Rectangle widths are already integer-valued but are floating
# type, so it helps to remove the trailing decimal point and 0 by
# converting width to int type
rect = rects[i]
width = freq[i]
rankStr = labels[i]
# The bars aren't wide enough to print the ranking inside
if width < 40:
# Shift the text to the right side of the right edge
xloc = 5
# Black against white background
clr = 'black'
align = 'left'
else:
# Shift the text to the left side of the right edge
xloc = -5
# White on magenta
clr = 'white'
align = 'right'
# Center the text vertically in the bar
yloc = rect.get_y() + rect.get_height() / 2
label = ax1.annotate(rankStr + " (" + str(freq[i]) + ")", xy=(width, yloc), xytext=(xloc, 0),
textcoords="offset points",
ha=align, va='center',
color=clr, weight='bold', clip_on=True)
plt.show()
一旦我输入了一些参数:
freq = [0.48, 0.40, 0.07, 0.05]
labels = ['Label 1', 'Label 2', 'Label 3', 'Label 4']
plot_results("Plot title", freq, labels)
我得到以下结果:
这些条似乎是自动排序的。我希望条形图按照标签在列表中的确切顺序出现(从顶部的“标签 1”开始,到底部的“标签 4”结束)。如何关闭此自动排序?
解决方案
推荐阅读
- mysql - 如何在 SQL 中为相同的 AgentID 选择下一个日期时间
- java - 如何将 WebElements 存储在数组中
- rest - 如何在 Microsoft Graph 中转义 Sharepoint 列名称?
- javascript - 比较两个不同单元格的值评估为 false - Google Apps 脚本
- java - 特殊字符问题:MQ 消息 PUT 错误:java.nio.charset.UnmappableCharacterException
- css - 媒体查询括号条件
- c# - 将数据从组合框和文本框插入 Datagridview 到特定行
- javascript - WooCommerce 加载更多按钮功能问题
- c# - 如何发送 HL7 ACK 消息作为 TCP 响应?
- django-rest-framework - 在将数据保存到数据库之前如何自定义 CreateModelMixin