【问题标题】:How can I display text over columns in a bar chart in matplotlib?如何在 matplotlib 条形图中的列上显示文本?
【发布时间】:2011-11-17 09:59:37
【问题描述】:

我有一个条形图,我想在每一列上显示一些文本,我该怎么做?

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    我相信这会为您指明正确的方向:

    http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html.

    你最感兴趣的部分是:

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

    文本的位置由高度函数或列的高度决定,放在每列顶部的数字由:'%d' %int(height)。因此,您需要做的就是创建一个字符串数组,称为“名称”,您希望将其放在列的顶部并进行迭代。请务必将格式更改为字符串 (%s) 而不是双精度。

    def autolabel(rects):
    # attach some text labels
        for ii,rect in enumerate(rects):
            height = rect.get_height()
            plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (name[ii]),
                    ha='center', va='bottom')
    autolabel(rects1)
    

    应该这样做!

    【讨论】:

    • 我试图理解它,但我想显示一个字符串,这就是它困扰我的地方。我弄乱了它,但我无法修改它以适合我的情况。
    • @cosmosis 如果 y 值相差很大(例如,最小值 0 和最大值 1300),1.02*height 将不起作用。有什么建议吗?
    • @ta.ft - 如果使用百分位数不起作用,请尝试添加一个固定数字,例如 height+20。另一种解决方案是在 for 循环中设置一个 if 循环,在其中指定 height1 = height * 1.02 if height height1 = height + 20 if height > 300。然后,在 plt.text 中,将 height 调用替换为 @ 987654329@.
    • @cosmosis 这是一个不错的解决方法,但仍不能保证栏和文本之间的距离始终相同。
    • @DhruvGhulati 这不会在图中传递,它会在直方图上方的特定高度生成文本,其中pltimport matplotlib.pyplot as plt 的简写。较低函数中的标签不需要读入,因为它们与直方图rects一起被枚举了,因此不需要读入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2019-06-22
    • 2021-02-06
    • 2020-06-19
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多