在matplotlib中创建发散的堆叠柱状图

13 投票
2 回答
11586 浏览
提问于 2025-04-18 03:10

我有一些数据列表,这些数据表示对李克特问题的回答,评分从1(非常不满意)到5(非常满意)。我想制作一个页面,展示这些列表,使用倾斜的堆叠水平条形图。不同的回答列表可能大小不一(比如,有人选择不回答某个问题)。以下是一个简单的数据示例:

likert1 = [1.0, 2.0, 1.0, 2.0, 1.0, 3.0, 3.0, 4.0, 4.0, 1.0, 1.0]
likert2 = [5.0, 4.0, 5.0, 4.0, 5.0, 3.0]

我希望能用类似下面的方式来绘制这些数据:

plot_many_likerts(likert1, likert2)

目前,我写了一个函数,可以遍历这些列表,并在同一个图形中将每个列表绘制成自己的子图,使用的是matplotlib库:

def plot_many_likerts(*lsts):
    #get the figure and the list of axes for this plot
    fig, axlst = plt.subplots(len(lsts), sharex=True)
    for i in range(len(lsts)):
        likert_horizontal_bar_list(lsts[i], axlst[i], xaxis=[1.0, 2.0, 3.0, 4.0, 5.0])
        axlst[i].axis('off')
    fig.show()

def likert_horizontal_bar_list(lst, ax, xaxis):
    cnt = Counter(lst)
    #del (cnt[None])
    i = 0
    colour_float = 0.00001
    previous_right = 0
    for key in sorted(xaxis):
        ax.barh(bottom=0, width=cnt[key], height=0.4, left=previous_right, color=plt.cm.jet(colour_float),label=str(key))
        i += 1
        previous_right = previous_right + cnt[key]
       colour_float = float(i) / float(len(xaxis))

这样做效果还不错,可以创建堆叠条形图,并且所有图的代表性大小相同(例如,宽度共享相同的坐标轴比例)。这是一个截图:

当前生成的效果 http://s7.postimg.org/vh0j816gn/figure_1.jpg

我希望能将这两个图中心对齐在数据集的众数的中点上(这些数据集的范围是相同的)。比如:

我想看到的效果 http://s29.postimg.org/z0qwv4ryr/figure_2.jpg

有没有什么建议可以让我实现这个目标?

2 个回答

7

我最近也需要为一些Likert数据制作一个分歧条形图。我采用的方法和@austin-cory-bart稍有不同。

我修改了画廊中的一个示例,然后创建了这个:

import numpy as np
import matplotlib.pyplot as plt


category_names = ['Strongly disagree', 'Disagree',
                  'Neither agree nor disagree', 'Agree', 'Strongly agree']
results = {
    'Question 1': [10, 15, 17, 32, 26],
    'Question 2': [26, 22, 29, 10, 13],
    'Question 3': [35, 37, 7, 2, 19],
    'Question 4': [32, 11, 9, 15, 33],
    'Question 5': [21, 29, 5, 5, 40],
    'Question 6': [8, 19, 5, 30, 38]
}


def survey(results, category_names):
    """
    Parameters
    ----------
    results : dict
        A mapping from question labels to a list of answers per category.
        It is assumed all lists contain the same number of entries and that
        it matches the length of *category_names*. The order is assumed
        to be from 'Strongly disagree' to 'Strongly aisagree'
    category_names : list of str
        The category labels.
    """
    
    labels = list(results.keys())
    data = np.array(list(results.values()))
    data_cum = data.cumsum(axis=1)
    middle_index = data.shape[1]//2
    offsets = data[:, range(middle_index)].sum(axis=1) + data[:, middle_index]/2
    
    # Color Mapping
    category_colors = plt.get_cmap('coolwarm_r')(
        np.linspace(0.15, 0.85, data.shape[1]))
    
    fig, ax = plt.subplots(figsize=(10, 5))
    
    # Plot Bars
    for i, (colname, color) in enumerate(zip(category_names, category_colors)):
        widths = data[:, i]
        starts = data_cum[:, i] - widths - offsets
        rects = ax.barh(labels, widths, left=starts, height=0.5,
                        label=colname, color=color)
    
    # Add Zero Reference Line
    ax.axvline(0, linestyle='--', color='black', alpha=.25)
    
    # X Axis
    ax.set_xlim(-90, 90)
    ax.set_xticks(np.arange(-90, 91, 10))
    ax.xaxis.set_major_formatter(lambda x, pos: str(abs(int(x))))
    
    # Y Axis
    ax.invert_yaxis()
    
    # Remove spines
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['left'].set_visible(False)
    
    # Ledgend
    ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),
              loc='lower left', fontsize='small')
    
    # Set Background Color
    fig.set_facecolor('#FFFFFF')

    return fig, ax


fig, ax = survey(results, category_names)
plt.show()

enter image description here

11

我需要为一些Likert数据制作一个发散条形图。我使用的是pandas,但即使不使用它,方法也大致相同。关键在于在开始时添加一个看不见的缓冲区。

likert_colors = ['white', 'firebrick','lightcoral','gainsboro','cornflowerblue', 'darkblue']
dummy = pd.DataFrame([[1,2,3,4, 5], [5,6,7,8, 5], [10, 4, 2, 10, 5]],
                     columns=["SD", "D", "N", "A", "SA"],
                    index=["Key 1", "Key B", "Key III"])
middles = dummy[["SD", "D"]].sum(axis=1)+dummy["N"]*.5
longest = middles.max()
complete_longest = dummy.sum(axis=1).max()
dummy.insert(0, '', (middles - longest).abs())

dummy.plot.barh(stacked=True, color=likert_colors, edgecolor='none', legend=False)
z = plt.axvline(longest, linestyle='--', color='black', alpha=.5)
z.set_zorder(-1)

plt.xlim(0, complete_longest)
xvalues = range(0,complete_longest,10)
xlabels = [str(x-longest) for x in xvalues]
plt.xticks(xvalues, xlabels)
plt.show()

这种方法有很多限制。首先,条形图不再有黑色轮廓,图例会多出一个空白元素。我只是把图例隐藏了(我觉得可能有办法只隐藏那个单独的元素)。我不太确定如何让条形图有轮廓而不把轮廓也加到缓冲元素上。

首先,我们确定一些颜色和虚拟数据。然后我们计算左边两个柱子的宽度和中间柱子一半的宽度(我知道这分别是“SD”、“D”和“N”)。我找出最长的柱子,并用它的宽度来计算其他柱子所需的差值。接下来,我在第一个柱子的位置插入这个新的缓冲柱,并给它一个空白标题(这让我感觉很糟糕,真心的)。为了保险起见,我还根据[2]的建议,在中间柱子的中间后面添加了一条垂直线(axvline)。最后,我通过调整x轴的标签来确保它有合适的刻度。

你可能想在左边留更多的水平空间——你可以通过增加“longest”来轻松做到这一点。

对齐的Likert数据

[2] Heiberger, Richard M. 和 Naomi B. Robbins. "为Likert量表和其他应用设计发散堆叠条形图。" 统计软件杂志 57.5 (2014): 1-32.

撰写回答