Fork me on GitHub

Seaborn绘制柱状图

基于Seaborn绘制柱状图

本文介绍的是如何使用seaborn来绘制各种柱状图

  • 基础柱状图
  • 水平柱状图
  • 标题设置
  • 基于DataFrame绘图
  • hue参数设置
  • 颜色处理
  • 多维度处理

导入库

Seaborn是matplotlib的高级封装,所以matplotlib还是要同时导入:

In [1]:

1
2
3
4
5
6
7
8
9
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')

导入内置数据

使用的是seaborn中内置的一份消费tips数据集:

In [2]:

1
2
tips = sns.load_dataset("tips")
tips.head()

基础柱状图

In [3]:

1
2
3
4
5
x = ["A","B","C"]
y = [1, 2, 3]

sns.barplot(x, y)
plt.show()

绘制水平柱状图:

1
2
3
4
5
6
7
# 水平柱状图

x = ["A","B","C"]
y = [1, 2, 3]

sns.barplot(y, x)
plt.show()

设置标题

In [14]:

1
2
3
4
5
6
7
x = ["A","B","C"]
y = [1, 2, 3]

fig = sns.barplot(x, y)
fig.set_title('title of seaborn')

plt.show()

指定x-y-data

In [5]:

1
2
3
4
# 通过DataFrame来指定

ax = sns.barplot(x="day", y="tip", data=tips)
plt.show()

hue参数

实现的分组显示数据

In [6]:

1
2
3
4
ax = sns.barplot(x="day",
y="total_bill",
hue="sex",
data=tips)

水平柱状图

In [7]:

1
2
3
ax = sns.barplot(x="total_bill",
y="day",
data=tips)

自定义顺序

In [8]:

1
2
3
4
5
ax = sns.barplot(x="total_bill",
y="day",
# 添加order参数,指定顺序
order=["Sat","Fri","Sun","Thur"], # 自定义
data=tips)

颜色处理

使用一种颜色

In [9]:

1
2
3
4
5
ax = sns.barplot(x="size",
y="total_bill",
data=tips,
color="salmon",
saturation=.5)

颜色渐变

In [10]:

1
2
3
4
ax = sns.barplot(x="size",
y="tip",
data=tips,
palette="Blues")

多维分组

In [11]:

1
2
3
4
5
6
7
8
g = sns.catplot(x="sex",
y="total_bill",
hue="smoker",
col="time",
data=tips,
kind="bar",
height=4,
aspect=.7)

True/False分组

In [12]:

1
2
tips["weekend"] = tips["day"].isin(["Sat", "Sun"])
tips

Out[12]:

In [13]:

1
2
3
4
5
ax = sns.barplot(x="day",
y="tip",
hue="weekend",
data=tips,
dodge=False)

本文标题:Seaborn绘制柱状图

发布时间:2022年06月28日 - 00:06

原始链接:http://www.renpeter.cn/2022/06/28/Seaborn%E7%BB%98%E5%88%B6%E6%9F%B1%E7%8A%B6%E5%9B%BE.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea