The method of displaying the y value on the seaborn histogram

1. In the old version of matplotlib, you can only add values ​​to the histogram one by one through plt.text. The plt.bar_label() function is added in the subsequent new version, which can be conveniently and quickly labeled. The method is as follows:

bar1 = plt.bar([1,2,3],[2,5,9])
plt.bar_label(bar1)

 

But if you want to operate on seaborn:

bar2 = sns.barplot([1,2,3],[2,3,4])
plt.bar_label(bar2)

 

The above operation reports an error, showing that the object does not have the attribute datavalues. It is guessed that the object passed to plt.bar_label is wrong. Explore the objects returned by plt.bar and sns.barplot:

It can be seen that the two objects are inconsistent. It can be seen that the input of plt.bar_label should be the BarContainer object, and the return of sns.barplot is the AxesSubplot object.

The correct way is as follows: Take out the containers attribute of AxesSubplot, get the iterator of the container object, traverse it or take out the container object separately and pass it to plt.bar_label.

bar2 = sns.barplot([1,2,3],[2,3,4])
plt.bar_label(bar2.containers[0])

 

Guess you like

Origin blog.csdn.net/weixin_46707493/article/details/126986829