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

您所在的位置:网站首页 sns柱状图 seaborn + matplotlib 画图(二): 柱状图,散点图

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

2023-10-02 23:17| 来源: 网络整理| 查看: 265

画图笔记第二篇,主要记录了柱状图和散点图的画法,同样使用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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3