系统:Windows 7
语言版本:Anaconda3-4.3.0.1-Windows-x86_64
编辑器:pycharm-community-2016.3.2
seaborn:0.7.1
- 这个系列讲讲Python的科学计算版块
- 今天讲讲seaborn模块:箱形图
Part 1:示例
- 已知
df_1
,有4列["p1", "p2", "p3", "p4", "from"]
- 根据
from
类别输出p1
的箱形图,就是以from
为分类标准,将p1列进行分类,对每类输出箱形图 - 不考虑from列,输出
"p1", "p2", "p3", "p4"
的箱形图
图1 p1
的箱形图

图2 "p1", "p2", "p3", "p4"
的箱形图

Part 2:代码
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
dict_1 = {
"p1": [0.5, 0.8, 1.0, 1.2, 1.5, 2.5, 0.9, 0.6, 1.3, 1.0,
1.3, 1.6, 1.9, 2.5, 4.2, 3.5, 2.2, 1.2, 1.5, 0.5],
"p2": [1.3, 2.8, 1.3, 1.4, 6.5, 2.5, 0.9, 0.6, 1.3, 1.0,
1.3, 1.6, 1.9, 2.5, 4.2, 3.5, 1.2, 1.2, 3.5, 2.5],
"p3": [2.5, 0.8, 1.3, 1.2, 1.5, 2.8, 1.9, 0.6, 1.3, 1.1,
1.3, 1.6, 1.1, 2.5, 4.2, 3.9, 2.2, 1.2, 1.5, 0.5],
"p4": [2.5, 0.8, 1.3, 1.2, 1.5, 3.8, 1.9, 0.6, 1.3, 1.1,
1.3, 1.6, 1.1, 2.5, 4.2, 3.9, 2.2, 1.2, 1.5, 0.5],
"from": ["sample1", "sample1", "sample1", "sample1", "sample1",
"sample2", "sample2", "sample2", "sample2", "sample2",
"sample3", "sample3", "sample3", "sample3", "sample3",
"sample4", "sample4", "sample4", "sample4", "sample4"]}
df_1 = pd.DataFrame(dict_1, columns=["p1", "p2", "p3", "p4", "from"])
print(df_1)
sns.set(style="ticks", color_codes=True)
sns.boxplot(x="from", y="p1", data=df_1, palette="Set2")
plt.show()
图3 代码截图

图4 df_1

Part 3:部分代码解读
-
sns.boxplot(x="from", y="p1", data=df_1, palette="Set2")
,生成结果对应图1-
x="from", y="p1"
表示以from列作为p1列的分组标准,对每组画出箱形图 -
data
数据源,是一个DataFrame -
palette
色板
-
-
若将上句替换为
sns.boxplot(data=df_1)
,对应图2 -
对比图2和图5,同样的数据不同的可视化展示,想表达的信息也会有区别
图5 cmap="hot_r"效果图

本文为原创作品,欢迎分享朋友圈
长按图片识别二维码,关注本公众号
Python 优雅 帅气

网友评论