seaborn + matplotlib 画图(二): 柱状图,散点图

画图笔记第二篇,主要记录了柱状图和散点图的画法,同样使用Iris数据集作为示例。
Seaborn 中文文档:https://seaborn.apachecn.org/#/README

seaborn + matplotlib 画图(一): 小提琴图,箱型图
seaborn + matplotlib 画图(二): 柱状图,散点图
seaborn + matplotlib 画图(三): 热图

1. 导入所需包

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

2. 载入Iris数据

df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
df.columns = ['sepal_length','sepal_width','petal_length','petal_width','class']
print(df.shape)
print(df.head())
print(df['class'].value_counts())

-----outputs-----
(150, 5)

   sepal_length  sepal_width  petal_length  petal_width        class
0           5.1          3.5           1.4          0.2  Iris-setosa
1           4.9          3.0           1.4          0.2  Iris-setosa
2           4.7          3.2           1.3          0.2  Iris-setosa
3           4.6          3.1           1.5          0.2  Iris-setosa
4           5.0          3.6           1.4          0.2  Iris-setosa

Iris-virginica     50
Iris-setosa        50
Iris-versicolor    50
Name: class, dtype: int64

3. 颜色和marker类型

这里贴了3个网站,是matplotlib预设的颜色和marker,方便我们选择颜色和marker形状。
Named colors: https://matplotlib.org/stable/gallery/color/named_colors.html
Colormaps: https://matplotlib.org/stable/tutorials/colors/colormaps.html
Markers: https://matplotlib.org/stable/api/markers_api.html
这里我先为3种不同的鸢尾花指定3种颜色,存放到字典里,方便后面使用。选择的颜色都是named colors里预设的。
另外,用一个列表存储3种鸢尾花的绘图顺序。

pal = {'Iris-setosa':'lightcoral','Iris-versicolor':'navajowhite','Iris-virginica':'cornflowerblue'}
class_order = ['Iris-setosa','Iris-versicolor','Iris-virginica']

4. barplot柱状图

普通柱状图

plt.figure(figsize=(5,5))
g = sns.barplot(data=df, x='class', y='sepal_length',        #传入数据
                linewidth=1.5,        #线宽
                palette=pal,        #颜色
                order=class_order,        #顺序
                saturation=1,        #颜色饱和度,默认0.75
                errwidth=2,        #error bar线粗细
                errcolor='.26',        #error bar 颜色,默认'.26'
                capsize=0.3,        #error bar的宽度
                ci='sd')          #float or "sd" or None, optional,默认95。使用数值设置置信区间,error bar表示置信区间;"sd":error bar表示标准差;None:不绘制error bar

ylabel = 'Sepal length'
plt.ylabel(ylabel, fontsize=18)
plt.yticks(fontsize=15)
plt.xlabel('')
plt.xticks(ticks=[0,1,2], labels=['Setosa','Versicolor','Virginiical'],
           fontsize=15, ha='center', va='top')
ax = plt.axes()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()

barplot

空心柱状图

plt.figure(figsize=(5,5))
g = sns.barplot(data=df, x='class', y='sepal_length',
                linewidth=5,
                facecolor='white', edgecolor='coral',        #颜色设置成白色
                order=class_order, saturation=1,
                errwidth=2,ci='sd', capsize=0.3)

ylabel = 'Sepal length'
plt.ylabel(ylabel, fontsize=18)
plt.yticks(fontsize=15)
plt.xlabel('')
plt.xticks(ticks=[0,1,2], labels=['Setosa','Versicolor','Virginiical'],
           fontsize=15, ha='center', va='top')
ax = plt.axes()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()
barplot

自定义颜色的柱状图
这里我们想展示30个样本的petal length,每种iris取前10个样本。这里最后一列的id是上一篇笔记中加入的。

df2 = pd.concat([df.iloc[:10,:],df.iloc[50:60,:],df.iloc[100:110,:]])
print(df2.shape)
print(df2.head())
print(df2['class'].value_counts())

-----outputs-----
(30, 6)
   sepal_length  sepal_width  petal_length  petal_width        class        id
0           5.1          3.5           1.4          0.2  Iris-setosa  setosa-1
1           4.9          3.0           1.4          0.2  Iris-setosa  setosa-2
2           4.7          3.2           1.3          0.2  Iris-setosa  setosa-3
3           4.6          3.1           1.5          0.2  Iris-setosa  setosa-4
4           5.0          3.6           1.4          0.2  Iris-setosa  setosa-5
Iris-setosa        10
Iris-virginica     10
Iris-versicolor    10
Name: class, dtype: int64
color_list = [pal[i] for i in df2['class']]
plt.figure(figsize=(10,5))
g = sns.barplot(y='petal_length', x='id', data=df2,
                palette=color_list)        #通过color_list自定义每个柱的颜色

ylabel = 'Petal length'
plt.ylabel(ylabel, fontsize=18)
plt.yticks(fontsize=15)
plt.xlabel('')
plt.xticks(fontsize=12, ha='right', va='center', rotation=90, rotation_mode='anchor')
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

import matplotlib.patches as mpatches        #创建图注
patches = [mpatches.Patch(color=color,label=iris) for iris,color in pal.items()]
ax.legend(handles=patches,
          fontsize=12, frameon=False,
          loc='center left', bbox_to_anchor=(0.05,0.85))

plt.show()
barplot

5. scatterplot散点图

以sepal length为x轴,petal length为y轴,绘制散点图。

point_size = []
plt.figure(figsize=(5,5))
sns.scatterplot(x='sepal_length',y='petal_length',data=df,        #传入数据
                alpha=1,        #透明度
                color='coral',        #颜色
                edgecolor=None,        #边线颜色,None则无边线
                s=80,        #点的大小
                marker='*')        #点的形状,更多形状参考上面的网址

xlabel,ylabel = 'Sepal length','Petal length'
plt.ylabel(ylabel, fontsize=18)
plt.yticks(fontsize=15)
plt.xlabel(xlabel, fontsize=18)
plt.xticks(fontsize=15)

plt.show()
scatterplot

根据鸢尾花的种类设置不同的颜色、marker类型和大小:

point_color = {'Iris-setosa':'lightcoral','Iris-versicolor':'navajowhite','Iris-virginica':'cornflowerblue'}
point_size = {'Iris-setosa':30,'Iris-versicolor':60,'Iris-virginica':90}
point_style = {'Iris-setosa':'X','Iris-versicolor':'v','Iris-virginica':'P'}
plt.figure(figsize=(5,5))
sns.scatterplot(x='sepal_length',y='petal_length', data=df,        #传入数据
                hue='class', palette=point_color,        #根据hue的列绘制不同颜色
                size='class', sizes=point_size,        #根据size的列绘制不同大小
                style='class', markers=point_style,        #根据style的列绘制不同marker类型
                alpha=0.75, edgecolor='k')        #设置透明度和边线颜色

xlabel,ylabel = 'Sepal length','Petal length'
plt.ylabel(ylabel, fontsize=18)
plt.yticks(fontsize=15)
plt.xlabel(xlabel, fontsize=18)
plt.xticks(fontsize=15)

plt.legend(loc='upper left',         #设置legend box的某一点为anchor
           bbox_to_anchor=(1,1),        #设置anchor在图像中的位置
           ncol=1,        #legend列数,默认为1
           title=None,        #标题,默认为None
           fontsize=12,        #字体大小
           markerscale=1.5,        # legend中marker相对图中marker的比例, 1表示相同
           markerfirst=True,        #marker是否在前
           borderpad=None,        #float,frame大小,默认为None
           labelspacing=None,        #float,默认为None,图注间的垂直距离
           handlelength=None,        #float,默认为None,图注长度
           handletextpad=None,        #float,默认为None,图注与文字间的距离
           columnspacing=None,        #float,默认None,列之间的距离 
           frameon=False,        #是否要边框
           shadow=False,        #shdow: frameon为True时,legend边框是否有阴影
           framealpha=1,        # frameon为True时,设置frame(底板)的透明度; ; 
           facecolor=None,        #frameon为True时,设置legend box的背景颜色
           edgecolor=None)         # frameon为True时,设置legend box的边框颜色
plt.show()
scatterplot
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容