如何在不排序条形图的情况下可视化水平条形图?

2024-04-25 23:39:50 发布

您现在位置: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)

我得到以下结果:

enter image description here

这些条似乎是自动排序的。我希望条以标签在列表中的确切顺序显示(从顶部的“标签1”开始,到底部的“标签4”结束)。如何关闭自动分拣


Tags: thetoinrectimportrightlabelstitle
1条回答
网友
1楼 · 发布于 2024-04-25 23:39:50

数据不是“排序”的,诀窍是从下到上绘制条形图

要解决此问题,请反转数据顺序,或者更简单地更改y轴的方向:

freq = [0.48, 0.40, 0.07, 0.05]
labels = ['Label 1', 'Label 2', 'Label 3', 'Label 4']

fig, ax = plt.subplots()
ax.barh(labels, freq)
ax.invert_yaxis()

enter image description here

相关问题 更多 >