简体   繁体   中英

How can I solve my show number overlap my bar-chart when I using matplotlib?

在此处输入图片说明

And this is my code below :

def generate_bar_chart(self, x_data, y_data, legend, pic_name):

        n = len(x_data)

        plt.bar(range(n), y_data, align='center', color='steelblue', alpha=0.8, label=legend)

        plt.xticks(range(n), x_data, rotation=90)

        for x, y in enumerate(y_data):
            plt.text(x, y+100, '%s' % round(y, 1), ha='center', rotation=90, alpha=0.8)
        plt.grid(axis='y', linestyle='-', alpha=0.8)
        plt.legend()
        plt.tight_layout()
        pic_file = os.path.join(self.pic_path, pic_name)
        plt.savefig(pic_file)
        plt.close()

mayber there something wrong with enumerate() and plt.text, please give me some advice, thanks!

I would update 2 things in how you are plotting this:

  1. set the text alignment - verticalalignment='bottom' (or the shorthand va ), which makes the label placement insensitive to the label length.

  2. use the plt.annotate instead of plt.text . For your use case, the parameters are very similar, but it is also robust to both the scale of the data and the current zoom level.

The xytext=(0,5) makes the text start in the center of your bar, and 5 points above it (also include textcoords='offset points').

for x, y in enumerate(y_data):
    plt.annotate('%s' % round(y, 1), xy=(x, y), 
        xytext=(0, 5), textcoords='offset points',
        va='bottom', ha='center', rotation=90)

For reference, to just achieve #1 can be done with plt.text :

for x, y in enumerate(y_data):
    plt.text(x, y+300, '%s' % round(y, 1), ha='center',
        va='bottom', rotation=90, alpha=0.8)

If I understand correctly, you want the numbers to be printed above the bars ? If so, then just modify the offset for y in the call to text(). Currently you add 100, but keep in mind this is expressed in axis coordinates, so 100 is still a small value considering the total range of your y axis. Try 500 for example.
In order to set a similar offset to all bars, you have to define your offset from a relative point of view. You could try 1.15 * y instead of y+100 in the text() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM