Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在水平堆叠条形图中显示精确小数_Python_Numpy_Matplotlib - Fatal编程技术网

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

Python 如何在水平堆叠条形图中显示精确小数,python,numpy,matplotlib,Python,Numpy,Matplotlib,我找到了一个在上创建堆叠条形图的代码 问题是图表中没有显示小数点。在我发现的代码中,列表中没有小数,但如果将它们更改为小数,则不会显示(请参见下面的代码)。 如果试图在ax.text(x,y,str(int(c))行中将str改为float,那么实际上显示的是小数,但它们都是0。 非常感谢 import numpy as np import matplotlib.pyplot as plt category_names = ['Strongly disagree', 'Disagree','

我找到了一个在上创建堆叠条形图的代码

问题是图表中没有显示小数点。在我发现的代码中,列表中没有小数,但如果将它们更改为小数,则不会显示(请参见下面的代码)。 如果试图在ax.text(x,y,str(int(c))行中将str改为float,那么实际上显示的是小数,但它们都是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)
将numpy导入为np
将matplotlib.pyplot作为plt导入
类别名称=[“强烈不同意”、“不同意”、“既不同意也不同意”
“同意”、“同意”、“强烈同意”]
结果={
‘问题1’:[(10)、(14.99)、(17.01)、(32)、(26)]
}
def调查(结果、类别名称):
标签=列表(results.keys())
data=np.array(列表(results.values()))
data_cum=data.cumsum(轴=1)
类别颜色=plt.get\u cmap('RdYlGn')(
np.linspace(0.15,0.85,data.shape[1]))
图,ax=plt.子批次(图尺寸=(9.2,5))
ax.invert_yaxis()
ax.xaxis.set_可见(False)
ax.set_xlim(0,np.sum(数据,轴=1).max())
对于枚举(zip(category_name,category_colors))中的i(colname,color):
宽度=数据[:,i]
开始=数据总和[:,i]-宽度
最大barh(标签、宽度、左=起点、高度=0.5、,
label=colname,color=color)
xcenters=起点+宽度/2
r、 g,b,u=颜色
text_color='white'如果r*g*b<0.5,则为'darkgrey'
对于枚举中的y,(x,c)(zip(x中心,宽度)):
ax.text(x,y,str(int(c)),ha='center',va='center',
颜色=文本(颜色)
ax.图例(ncol=len(类别名称),bbox-to-anchor=(0,1),
loc='左下角',fontsize='small')
返回无花果,斧头
调查(结果、类别名称)
编写
str(int(c))
时,首先将数字转换为整数,从而删除小数,然后将其转换为字符串。要获得所需的输出,请使用
str(c)
,或者如果您希望能够更好地控制数字的格式(如选择小数点后的位数)将
str(int(c))
替换为
'{.2f}'。格式(c)

category_name=[“强烈不同意”、“不同意”、“既不同意也不同意”、“同意”、“强烈同意”]
结果={
‘问题1’:[(10)、(14.99)、(17.01)、(32)、(26)]
}
def调查(结果、类别名称):
标签=列表(results.keys())
data=np.array(列表(results.values()))
data_cum=data.cumsum(轴=1)
类别颜色=plt.get\u cmap('RdYlGn')(
np.linspace(0.15,0.85,data.shape[1]))
图,ax=plt.子批次(图尺寸=(9.2,5))
ax.invert_yaxis()
ax.xaxis.set_可见(False)
ax.set_xlim(0,np.sum(数据,轴=1).max())
对于枚举(zip(category_name,category_colors))中的i(colname,color):
宽度=数据[:,i]
开始=数据总和[:,i]-宽度
最大barh(标签、宽度、左=起点、高度=0.5、,
label=colname,color=color)
xcenters=起点+宽度/2
r、 g,b,u=颜色
text_color='white'如果r*g*b<0.5,则为'darkgrey'
对于枚举中的y,(x,c)(zip(x中心,宽度)):
text(x,y,“{.2f}.”格式(c),ha='center',va='center',
颜色=文本(颜色)
ax.图例(ncol=len(类别名称),bbox-to-anchor=(0,1),
loc='左下角',fontsize='small')
返回无花果,斧头
调查(结果、类别名称)
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, '{:.2f}'.format(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)