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]:
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]:
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]:
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()
'Data visualization with python' 카테고리의 다른 글
| [Python] seaborn - sns.relplot (lineplot, scatterplot 한방에 해결) (0) | 2021.01.26 |
|---|---|
| [Python] seaborn 데이터시각화 graph 종류 총 정리 (0) | 2021.01.04 |