如何在水平堆积条形图中显示精确的小数

ntal_barchart_distribution.html 上找到了创建堆叠条形图的代码。


问题是图中未显示小数位。在代码中,我发现列表中没有小数,但如果将它们更改为小数,则不会显示(参见下面的代码)。如果尝试将 str 更改为在 ax.text(x, y, str(int(c)) 行中浮动。这实际上显示小数,但它们都是 0。非常感谢。


import numpy as np

import matplotlib.pyplot as plt



category_names = ['Strongly disagree', 'Disagree','Neither agree nor   

agree', 'agree', 'Strongly agree']


results = {

    'Question 1': [(10), (14.99), (17.01), (32), (26)]

}



def survey(results, category_names):

    labels = list(results.keys())

    data = np.array(list(results.values()))

    data_cum = data.cumsum(axis=1)

    category_colors = plt.get_cmap('RdYlGn')(

        np.linspace(0.15, 0.85, data.shape[1]))


    fig, ax = plt.subplots(figsize=(9.2, 5))

    ax.invert_yaxis()

    ax.xaxis.set_visible(False)

    ax.set_xlim(0, np.sum(data, axis=1).max())


    for i, (colname, color) in enumerate(zip(category_names, category_colors)):

        widths = data[:, i]

        starts = data_cum[:, i] - widths

        ax.barh(labels, widths, left=starts, height=0.5,

                label=colname, color=color)

        xcenters = starts + widths / 2


        r, g, b, _ = color

        text_color = 'white' if r * g * b < 0.5 else 'darkgrey'


        for y, (x, c) in enumerate(zip(xcenters, widths)):

            ax.text(x, y, str(int(c)), ha='center', va='center',

                color=text_color)

    ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),

              loc='lower left', fontsize='small')


    return fig, ax



survey(results, category_names)


慕斯王
浏览 107回答 1
1回答

jeck猫

编写str(int(c))时,首先将数字转换为整数,从而去掉小数,然后将其转换为字符串。要获得所需的输出,请使用str(c),或者如果您希望能够更好地控制数字的格式(例如选择小数点后的位数),请替换str(int(c))为'{:.2f}'.format(c)category_names = ['Strongly disagree', 'Disagree','Neither agree nor agree', 'agree', 'Strongly agree']results = {&nbsp; &nbsp; 'Question 1': [(10), (14.99), (17.01), (32), (26)]}def survey(results, category_names):&nbsp; &nbsp; labels = list(results.keys())&nbsp; &nbsp; data = np.array(list(results.values()))&nbsp; &nbsp; data_cum = data.cumsum(axis=1)&nbsp; &nbsp; category_colors = plt.get_cmap('RdYlGn')(&nbsp; &nbsp; &nbsp; &nbsp; np.linspace(0.15, 0.85, data.shape[1]))&nbsp; &nbsp; fig, ax = plt.subplots(figsize=(9.2, 5))&nbsp; &nbsp; ax.invert_yaxis()&nbsp; &nbsp; ax.xaxis.set_visible(False)&nbsp; &nbsp; ax.set_xlim(0, np.sum(data, axis=1).max())&nbsp; &nbsp; for i, (colname, color) in enumerate(zip(category_names, category_colors)):&nbsp; &nbsp; &nbsp; &nbsp; widths = data[:, i]&nbsp; &nbsp; &nbsp; &nbsp; starts = data_cum[:, i] - widths&nbsp; &nbsp; &nbsp; &nbsp; ax.barh(labels, widths, left=starts, height=0.5,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label=colname, color=color)&nbsp; &nbsp; &nbsp; &nbsp; xcenters = starts + widths / 2&nbsp; &nbsp; &nbsp; &nbsp; r, g, b, _ = color&nbsp; &nbsp; &nbsp; &nbsp; text_color = 'white' if r * g * b < 0.5 else 'darkgrey'&nbsp; &nbsp; &nbsp; &nbsp; for y, (x, c) in enumerate(zip(xcenters, widths)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ax.text(x, y, '{:.2f}'.format(c), ha='center', va='center',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color=text_color)&nbsp; &nbsp; ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loc='lower left', fontsize='small')&nbsp; &nbsp; return fig, axsurvey(results, category_names)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python