Public number: You Er Hut
Author: Peter
Editor: Peter
Hello everyone, my name is Peter~
This article describes how to use seaborn to draw various histograms
- Basic histogram
- horizontal histogram
- Title settings
- Drawing based on DataFrame
- hue parameter setting
- color processing
- multi-dimensional processing
A graph drawn by Seaborn that I like very much:
import library
Seaborn is an advanced package of 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')
Import built-in data
Using a consumer tips dataset built into seaborn:
In [2]:
tips = sns.load_dataset("tips")
tips.head()
Basic histogram
In [3]:
x = ["A","B","C"]
y = [1, 2, 3]
sns.barplot(x, y)
plt.show()
Plot a horizontal histogram:
# 水平柱状图
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 xy-data
In [5]:
# 通过DataFrame来指定
ax = sns.barplot(x="day", y="tip", data=tips)
plt.show()
hue parameter
Implemented grouped display data
In [6]:
ax = sns.barplot(x="day",
y="total_bill",
hue="sex",
data=tips)
horizontal histogram
In [7]:
ax = sns.barplot(x="total_bill",
y="day",
data=tips)
custom order
In [8]:
ax = sns.barplot(x="total_bill",
y="day",
# 添加order参数,指定顺序
order=["Sat","Fri","Sun","Thur"], # 自定义
data=tips)
color processing
use a 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")
Multidimensional 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)