Search code examples
pythonpandasaxes

Not showing the total number of size in each bar in its graph in Python?


I have a problem about showing the numbers above each bar in its graph.

Here is my dafaframe which is shown below.

ID  SEX count
6   Secret Identity Male Characters 1751
3   Public Identity Male Characters 1662
1   Public Identity Female Characters   765
4   Secret Identity Female Characters   625
2   Public Identity Genderless Characters   11
0   Identity Unknown    Male Characters 9
5   Secret Identity Genderless Characters   5

Here is my code function which is shown below.

def show_values_on_bars(axs, h_v="v", space= 0.4):
    
    def _show_on_single_plot(ax):
        if h_v == "v":
            for p in ax.patches:
                _x = p.get_x() + p.get_width() / 2
                _y = p.get_y() + p.get_height()
                value = int(p.get_height())
                ax.text(_x, _y, value, ha="center", fontsize=18) 
        elif h_v == "h":
            for p in ax.patches:
                _x = p.get_x() + p.get_width()
                _y = p.get_y() + p.get_height() - float(space)                
                value = int(p.get_width())
                ax.text(_x, _y, value, ha="left", fontsize=18)

    if isinstance(axs, np.ndarray):
        for idx, ax in np.ndenumerate(axs):
            _show_on_single_plot(ax)
    else:
        _show_on_single_plot(axs)

When I run this code snippets defined below, I got an error message which is shown below.

graph_3 = sns.barplot(data = dc_df, 
            x = "ID" , 
            y = "count", ax=a[1,0], hue='SEX')

show_values_on_bars(graph_3, "v", 0.3)

The error : value = int(p.get_height()) -> ValueError: cannot convert float NaN to integer

How can I fix it?


Solution

  • Kindly check it and assign value to 0 is p.get_height() is NaN.

    import numpy as np
    
    def show_values_on_bars(axs, h_v="v", space= 0.4):
        
        def _show_on_single_plot(ax):
            if h_v == "v":
                for p in ax.patches:
    
                    value = 0
                    if not np.isnan(p.get_height()):
                        value = int(p.get_height())
    
                    _x = p.get_x() + p.get_width() / 2
                    _y = p.get_y() + value
    
                    ax.text(_x, _y, value, ha="center", fontsize=18)