【问题标题】:Y values on each stacked bar using matplotlib使用 matplotlib 在每个堆叠条上的 Y 值
【发布时间】:2015-10-05 14:04:14
【问题描述】:

对在图表上显示实际值有疑问。我确实有一个打印的图表,需要显示每个堆叠条的值。如何显示这些值?

我尝试了ax.text 函数,但它没有给出预期的结果(见图)。由于图表标准化为 1,我需要显示每个堆叠条的实际值(顶部是总数,它应该拆分为每个条-第一个条应该有 1 个数字 7,第二个条应该有 3 个数字,其中数字41被每个颜色条的大小分割)。可以这样做吗?

我的代码如何想出多个堆叠条:

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

p = [] # list of bar properties
def create_subplot(matrix, colors, axis):
    bar_renderers = []
    ind = np.arange(matrix.shape[1])
    bottoms = np.cumsum(np.vstack((np.zeros(matrix.shape[1]), matrix)), axis=0)[:-1]
    for i, row in enumerate(matrix):
        print bottoms[i]
        r = axis.bar(ind, row, width=0.5, color=colors[i], bottom=bottoms[i])
        bar_renderers.append(r)
        autolabel(r)
    #axis.set_title(title,fontsize=28)
    return bar_renderers

p.extend(create_subplot(nauja_matrica,spalvos, ax))

【问题讨论】:

    标签: python matplotlib charts stacked-chart


    【解决方案1】:

    您可以使用ax.text 函数显示每个堆叠条的值。几乎不需要对您的代码进行更正即可获得所需的结果。实际上,只需将autolabel 函数替换为以下代码即可:

    def autolabel(rects):
        # Attach some text labels.
        for rect in rects:
            ax.text(rect.get_x() + rect.get_width() / 2.,
                    rect.get_y() + rect.get_height() / 2.,
                    '%f'%rect.get_height(),
                    ha = 'center',
                    va = 'center')
    

    它将纠正标签的垂直定位并给出:

    如果您想更改标签以获取非标准化值,那么还有一些工作要做。最简单的解决方案是将附加参数values(包含非标准化值)传递给autolabel 函数。代码将是:

    def autolabel(rects, values):
        # Attach some text labels.
        for (rect, value) in zip(rects, values):
            ax.text(rect.get_x() + rect.get_width() / 2.,
                    rect.get_y() + rect.get_height() / 2.,
                    '%d'%value,
                    ha = 'center',
                    va = 'center')
    

    希望对你有帮助。

    【讨论】:

    • 非常感谢非常感谢!!你是救生员;)
    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    相关资源
    最近更新 更多