This article is about how to use seaborn to draw various bar charts
-
Base Bar Chart
-
Horizontal Bar Chart
-
Title Settings
-
DataFrame based drawing
-
hue parameter setting
-
Color processing
-
Multi-dimensional processing
Personally, I like the graphics drawn by Seaborn:
Import Library
Seaborn is a high-level wrapper for matplotlib, so matplotlib still needs to be imported at the same time:
In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_theme(style="whitegrid")
sns.set_style('darkgrid')
Importing built-in data
A built-in dataset of consumer tips in seaborn is used:
In [2]:
tips = sns.load_dataset("tips")
tips.head()
Base Bar Chart
In [3]:
x = ["A","B","C"]
y = [1, 2, 3]
sns.barplot(x, y)
plt.show()
Plot horizontal bar graphs:
# Horizontal Bar Chart
x = ["A","B","C"]
y = [1, 2, 3]
sns.barplot(y, x)
plt.show()
Set title
In [14]:
x = ["A","B","C"]
y = [1, 2, 3]
fig = sns.barplot(x, y)
fig.set_title('title of seaborn')
plt.show()
Specify x-y-data
In [5]:
# Specify by DataFrame
ax = sns.barplot(x="day", y="tip", data=tips)
plt.show()
hue parameters
Implemented group display data
In [6]:
ax = sns.barplot(x="day",
y="total_bill",
hue="sex",
data=tips)
Horizontal Bar Chart
In [7]:
ax = sns.barplot(x="total_bill",
y="day",
data=tips)
Customized order
In [8]:
ax = sns.barplot(x="total_bill", y="day", # Add the order parameter to specify the order order=["Sat","Fri","Sun","Thur"], # Customization
data=tips)
Color processing
Use one color
In [9]:
ax = sns.barplot(x="size",
y="total_bill",
data=tips,
color="salmon",
saturation=.5)
Color gradient
In [10]:
ax = sns.barplot(x="size",
y="tip",
data=tips,
palette="Blues")
Multi-dimensional grouping
In [11]:
g = sns.catplot(x="sex",
y="total_bill",
hue="smoker",
col="time",
data=tips,
kind="bar",
height=4,
aspect=.7)
True/False grouping
In [12]:
tips["weekend"] = tips["day"].isin(["Sat", "Sun"])
tips
Out[12]:
In [13]:
ax = sns.barplot(x="day",
y="tip",
hue="weekend",
data=tips,
dodge=False)