0

Hello friends I am creating a bar chart using seaborn or matplotlib. I make a successful graph, but I don't know how to display y bar values on the plot. Please give me suggestion and different techniques to display y-bar values on the plot.

Please help me to solve the question.

Thank you

plt.figure(figsize = (10,5))
sns.countplot(x='subject',data=udemy,hue='is_paid')

img

Mario
  • 1,631
  • 2
  • 21
  • 51
  • 1
    [Seaborn: countplot() with frequencies](https://stackoverflow.com/questions/33179122/seaborn-countplot-with-frequencies) I find this answer to be very helpful – r-beginners May 30 '20 at 13:36
  • See the autolabel function in [this example](https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html) – JohanC May 30 '20 at 14:15
  • Does this answer your question? [How can I display text over columns in a bar chart in matplotlib?](https://stackoverflow.com/questions/7423445/how-can-i-display-text-over-columns-in-a-bar-chart-in-matplotlib) – JohanC May 30 '20 at 14:16

2 Answers2

0

Unfortunately countplot in seaborn doesn't allow both x and y values to be passed, only one can be passed per plot.

Have you tried a different chart? e.g. plt.bar() and setting the xticks and yticks to the values you want?

0

Short answer: You need customized auto label mechanism.

First let's make it clear. If you mean by

I don't know how to display y bar values on the plot

  • that on bars (inner), then this answer can be helpful.

  • that on top of bars (outer), except for this answer for seaborn, there are some auto label solutions here you can use it as well as this example. Recently if you install the new matpotlib v. 3.4.0 you can use bar_label()Ref..

I can also offer you my approach inspired by this matplotlib documenetation using manual adjustment for the best fit to print value/text over bars in the bar chart using matplotlib in form of function:

from matplotlib import pyplot as plt
import numpy as np


def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
    

    # Check if colors where provided, otherwhise use the default color cycle
    if colors is None:
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

    # Number of bars per group
    n_bars = len(data)

    # The width of a single bar
    bar_width = total_width / n_bars

    # List containing handles for the drawn bars, used for the legend
    bars = []

    # Iterate over all data
    for i, (name, values) in enumerate(data.items()):
        # The offset in x direction of that bar
        x_offset = (i - n_bars / 2) * bar_width + bar_width / 2

        # Draw a bar for every value of that type
        for x, y in enumerate(values):
            bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])

        # Add a handle to the last drawn bar, which we'll need for the legend
        bars.append(bar[0])

    # Draw legend if we need
    if legend:
        ax.legend(bars, data.keys())


if __name__ == "__main__":
    # Usage example:
    data = {
        "False": [100.16,  30.04, 50.04, 120.19],
        "True": [1100.08,  600.06, 650.06, 1050.17],
        #"RMSE":[0.39,  0.19, 0.20, 0.44,  0.45,  0.26],
            }

    fig, ax = plt.subplots(figsize=(8, 6))
    
    y_pos = np.arange(len(objects))
    for i, v in enumerate(data['False']):
        plt.text(y_pos[i] - 0.35, v + 10.213, str(v))

    for i, v in enumerate(data['True']):
        plt.text(y_pos[i] + 0.05, v + 10.213, str(v))


    #plt.rc('font', **font)
    bar_plot(ax, data, total_width=.8, single_width=.9)
    #font = font_manager.FontProperties(family='Comic Sans MS', weight='bold', style='normal', size=16)
    font = {'family' : 'normal',
            'weight' : 'bold',
            'size'   : 15,
             'family':'Times New Roman'}
    #font = {'family':'Times New Roman', 'weight' :'normal','size':15}
    
    ax.set_xticklabels( ('0',' ','Business Finance',' ','Graphic Design',' ', 'Musical Instruments',' ', 'Web Development') , rotation=45, ha="right")#, **font )
    #ax.set_yticklabels( data['MSE'] ,**font )
    ax.set_ylabel('Count  ')#, **font)
    ax.set_xlabel('Subject  ')#, **font)
    ax.set_title('Figure 10/ Table 6 for is_paid')#, **font)
    #ax.legend().set_visible(False)
    plt.ylim((0.0, 1500.0))
    plt.show()

Output:

img

Mario
  • 1,631
  • 2
  • 21
  • 51