본문 바로가기

Data visualization with python

[Python] matplotlib pyplot - barplot with annotation

20210305_barplot_with_text

Chapter3. matplotlib barplot with text

This time, I will make barplot with pyplot of matplotlibrary in a very easy way

Import basic library

In [29]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

Set font-size of plt

In [38]:
SMALL_SIZE = 15
MEDIUM_SIZE = 18 
BIGGER_SIZE = 21 
plt.rc('font', size=SMALL_SIZE) # controls default text sizes 
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title 
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels 
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels 
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels 
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize 
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title

Load dataset 'tips'

In [39]:
tips = sns.load_dataset('tips')
tips.head()
Out[39]:
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

Basic parameter of ax.bar

In [42]:
a=tips['sex'].value_counts()

fig, ax = plt.subplots(1,1, figsize=(5, 5))
ax.bar(a.index, a)
# bottom: The y coordinate(s) of the bars bases
Out[42]:
<BarContainer object of 2 artists>

Make it more beautiful - modify ( color, edgecolor, linewidth )

In [43]:
fig, ax = plt.subplots(1,1, figsize=(5, 5))
ax.bar(a.index, a, width=0.8, edgecolor='darkgray', color='#d4dddd', linewidth=0.7)
Out[43]:
<BarContainer object of 2 artists>

Make it more detailed

In [74]:
fig, ax = plt.subplots(1,1, figsize=(5, 5))
ax.bar(a.index, a, width=0.8, edgecolor='darkgray', color='#d4dddd', linewidth=0.7)

# Tag label of y-value to your bar 
for i in a.index:
    ax.annotate(f"{a[i]}", # what to express
                   xy=(i, a[i]+15), # location x-axis, y-axis
                   va = 'center', ha='center', fontweight='bold', fontsize=SMALL_SIZE, fontfamily='sans-serif',
                   color='blue')

# Make border lines invisible
for s in ['top', 'left', 'right']:
    ax.spines[s].set_visible(False)

# Set y-limit
ax.set_ylim(0, 200)

# Can change xticklabels artificially
#ax.set_xticklabels(a.index, fontfamily='serif')

# Can change yticklabels artificially
#ax.set_yticklabels(np.arange(0, 200, 100),fontfamily='serif')

# Set title
fig.text(0.22, 0.95, # locate title
         'Age Distribution', # Name of title
         fontsize=BIGGER_SIZE, fontweight='bold', fontfamily='serif')

# Set grid
ax.grid(axis='y', 
        linestyle='-', 
        alpha=0.4) # Transparency
ax.set_axisbelow(True) # Make grid to go behind
# ax.grid(axis='x', linestyle='-', alpha=0.4) 

plt.show()