【matplotlib】数据可视化之散点图、折线图、柱状图、条形图、饼图、箱线图

本文详细介绍了使用Matplotlib进行数据可视化的基础知识与实践技巧。包括函数式与面向对象式的绘图方式,掌握matplotlib.pyplot的基本用法,如创建画布、添加内容及图形存储等。此外还介绍了散点图、折线图、柱状图等多种图表的制作方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

matplotlib数据可视化基础

作图


一、感受两种绘图方式

  1. 函数式作图(pyplot)
    由于函数式作图是使用经过封装后的函数来作图,所以很多时候函数式作图看起来比较方便。
    1. 整个matploblib包是由一系列由从属关系的对象构成的,函数式作图掩盖了原有的从属关系
    2. 个性化定制能力不如面对对象作图的方法强大,(因为面向对象作图是最底层的作图方法,几乎能做一切的图,只是操作可能略显繁琐)
  2. 面向对象作图(ojbject oriented)
    fig,ax=plt.subplots()
    生成一个figure对象和axes对象
    ax.plot(x,y)
    在这个坐标系axes上添加一个数据源为x,y的折线图
  3. matplotlib图像的组成结构
    Matplotlib 是一个 Python 的 2D绘图库,通过 Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。

1.1 导入需要的库

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#初步探究matplotlib.pyplot库
#dir(plt)
'''
'Subplot'\ 'axvline'\'rc'\ 'cm'\'xlim'\ 'ylim'\'xticks'\ 'yticks'\'xscale'\'yscale'.....
可能用到的部分
'''

#help(plt.axvline)
'''
axvline(x=0, ymin=0, ymax=1, **kwargs)
    Add a vertical line across the axes.在坐标轴上加一条垂直线。
x=0:默认线,可修改0的值
ymin:垂直线的下端点
ymax:垂直线的上端点
'''

1.2函数式作图


x=np.arange(5)  #一维数组
y=[1,5,3,7,9]   #列表
plt.plot(x,y)   #list-alike
plt.xlabel('x')
plt.ylabel('y')
plt.title('xy_plot')

z=pd.Series([2,4,8,8,10]) #一维序列series
plt.plot(x,z)

在这里插入图片描述

1.3面向对象式作图

#(1)生成figure和axes对象
fig,ax=plt.subplots()         #第一个参数是figure,第二个参数是axes
#(2)在坐标系上画图
ax.plot(x,y)
#(3)添加其他说明信息            #对应函数式作图
ax.set_xlabel('i am x')         #plt.xlabel('x')
ax.set_ylabel('i an y')         #plt.ylabel('y')
ax.set_title('xy_plot')         #plt.title('xy_plot')

在这里插入图片描述

在这里插入图片描述

二、掌握matplotlib.pyplot的基础用法

2.1 创建画布(figure)与创建子图(axes)

  • help(plt.Figure)
class Figure(matplotlib.artist.Artist)
|  Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, 
          tight_layout=None, constrained_layout=None)
figsize:(宽度,高度)-2个浮点数构成的元组
dpi:
facecolor:
edgecolor:边颜色
linewidth:线宽度
类figure的内置函数有:add_artist()\add_axes()\add_axobserver()\add_gridspec()\add_subplot()\align_labels()\align_xlabels()\
                     align_ylabels()\clear()\clf()\colorbar()\delaxes()\draw()\gca()\legend()\
gca(self, **kwargs)
|  Get the current axes, creating one if necessary.获取当前坐标轴,如果没有则创建一个新的
  • 先画图–> 后子图
fig1=plt.figure()           #创建的是画布
ax2=fig1.add_subplot(1,2,2)  #创建的是子图 (行,列,索引)

该方式用来创建一个画布上多个图片

  • 举个栗子
#plt.subplots()与fig.add_subplot()

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
#生成第一个画布(在一张图中用plt.subplots画多子图[axes])
fig1, (ax1, ax2) = plt.subplots(1, 2,figsize=(8,5),sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

#生成第二画布(在一张图中用figure.add_subplot画多个子图【axes】)
fig2=plt.figure(figsize=(16,5),dpi=80)     #长8宽5,像素80
ax3=fig2.add_subplot(131
                       # ,projection='polar'
                       # ,sharex=ax1
                       # ,facecolor='red'
                       # ,label='fig.plt.add_subplot'
                       )
ax3.scatter(x,y,c='green')
ax4=fig2.add_subplot(132)
ax4.plot(x,y,c=plt.cm.Set1(3))
plt.show()

在这里插入图片描述
在这里插入图片描述

2.2 添加画布内容

函数名称函数作用
plt.title在当前图行中添加标题,可以指定标题的名称、位置、颜色、字体大小等参数
plt.xlabel在当前图形中添加x轴的名称,可以指定位置、颜色、字体大小等参数
plt.ylabel在当前图形中添加y轴的名称,可以指定位置、颜色、字体大小等参数
plt.xlim指定当前图行x轴的范围,只能确定一个数值区间,而无法使用字符串标识
plt.ylim指定当前图行y轴的范围,只能确定一个数值区间,而无法使用字符串标识
plt.xticks指定x轴刻度的数目与取值
plt.yticks指定y轴刻度的数目与取值
plt.legend指定当前图形的图例,可以指定图例的大小、位置、标签。

2.3 存储与展示图形

plt.savafig保存绘制的图片,可以指定图片的分辨率、边缘的颜色等参数
plt.show在本机显示图形。
savefig(fname, *, dpi='figure', format=None, metadata=None,
              bbox_inches=None, pad_inches=0.1,
              facecolor='auto', edgecolor='auto',
              backend=None, **kwargs
参数描述
fname指定格式图片或者指定文件位置
dpi画质
facecolor 和 edgecolor默认为白色
Orientation横向或者纵向
papertype纸张类型
format如png、pdf
transparent图片背景透明
bbox_inches图表多余的空白区去除
pad_inches保存图形周围填充
不留图片两边的旁白
plt.savefig("MAEandRMSE.png",bbox_inches='tight')  #保存的时候不要留旁边的空白 

2.4 rc参数

pyplot使用rc配置文件来定义图形的各种默认属性,被称为rc参数或rc配置。在pyplot中几乎所有的默认属性都可以控制的。

axes.unicode_minus字符显示
font.sans-serif设置字体
xtick/ytick横/纵轴>
xtick.labelsize/ytick.labelsize横轴/纵轴字体大小
xtick.major.size/ytick.major.sizex/y轴字体大小
axes(figure中的子图)>
axes.titlesize子图的标题大小
axes.labelsize子图的标签大小
line线条样式>
linesstyle线条样式
line.linestyle线条宽度
lines.linewidth
figure/savefig(图像/图片)>
figure.dpi图像分辨率
figure.figsize图像显示大小
savefig.dpi图片像素

详细的rc参数:https://my.oschina.net/swuly302/blog/94805

通过matplotlib的方式查看rc参数:见连接

  • rc中的等价
import matplotlib
#以下三者等价
print(matplotlib.rc_params())
print(matplotlib.rcParamsDefault)
print(matplotlib.rcParams)
  • 修改rc相关配置
#方式一
matplotlib.rcParams['lines.linewidth']=2\
matpiotlib.rcParams['color']='r'
#方法二
matplotlib.rcParams('lines',linewidth=4,color='g')
#恢复默认参数
matplotlib.rcdefaults()
#从已有的文件更新
matplotlib.cr_file()
          |

2.5 颜色相关知识

  • matplotlib.colors模块的架构如下图所示
  • img
      • RGB三元数或颜色名称-使用相同的颜色绘制所有标记
    • 由RGB三元数组组成三列矩阵shape(N,3)-对每个标记使用不同的颜色。矩阵的每行行为对应标记指定一种RGB三元颜色。行数等于x

    • 向量-对每个标记使用不同的颜色,并以线性方式将c中的值映射到当前颜色图中的颜色。c的长度等于x.要更改坐标区的颜色图,请使用colormap函数

    • plt.scatter(...,cmap=plt.cm.nipy_spectral,...)中与matplotlib.cm是同一个文件夹。说明参数使用相同。

      help(plt.cm)
      class ScalarMappable(builtins.object)
           |  ScalarMappable(norm=None, cmap=None)
         这是一个mixin类,用于支持RGBA映射的标量数据。ScalarMappable在从给定的颜色映射返回RGBA颜色之前使用数据标准化
      
    • 有多个内置函数

      matplotlib.cm.get_cmap(name=None, lut=None)
      matplotlib.cm.register_cmap(name=None, cmap=None, data=None, lut=None)
      matplotlib.cm.revcmap(data)
      
    • 有多个数据对象

    • Accent = <matplotlib.colors.ListedColormap object>
      Accent_r = <matplotlib.colors.ListedColormap object>
      Blues = <matplotlib.colors.LinearSegmentedColormap object>
      Blues_r = <matplotlib.colors.LinearSegmentedColormap object>
      BrBG = <matplotlib.colors.LinearSegmentedColormap object>
       。。。
      Set1 = <matplotlib.colors.ListedColormap object>
      Set1_r = <matplotlib.colors.ListedColormap object>
      Set2 = <matplotlib.colors.ListedColormap object>
      。。。
      
    • cm.Set1()的颜色

      #用返回的颜色作图
      color1 = plt.cm.Set1(1)
      color2 = plt.cm.Set2(1)
      color3 = plt.cm.Set3(1)
      print(color1, '\n', color2, '\n', color3)
      
      plt.scatter(x=[2, 3, 4], y=[2, 3, 4], c=[color1, color2, color3], marker='*', s=200)
      

在这里插入图片描述

  • 查看plt.cm.Set1()的颜色区别

    import matplotlib.pyplot as plt
    # 用cm.Set1,cm.Set2,cm.Set3返回不同颜色
    for i in range(0, 20):
        color = plt.cm.Set1(i)
        # color = plt.cm.Set2(i)
        # color = plt.cm.Set3(i)
        print('color', i, color)
        plt.scatter(i, i, c=color, marker='^', s=200)
    plt.show()
    

在这里插入图片描述

  • help(plt.cm.jet)
    class LinearSegmentedColormap(Colormap)
     |  LinearSegmentedColormap(name, segmentdata, N=256, gamma=1.0)
     线性分段颜色图
     查找表是对每一个主色采用线性插值的方法生成的,0-1区域被划分成任意数量的段。
    
    #举例说明plt.cm.jet的性质
    unique=[3,4,7,8,9,10]
    colors=[plt.cm.jet(i/max(unique)*0.8) for i in unique ]  #plt.cm.jet线性插值,颜色由冷色调到暖色调
    colors_=[plt.cm.jet(i/max(unique)) for i in unique]
    print(colors)  #查看颜色的表示方式
    fig,(ax1,ax2)=plt.subplots(1,2,figsize=[8,5],dpi=80,sharey=True)
    ax1.scatter(x=[1,2,3,4,5,6],y=[3,4,5,6,7,8],c=colors,marker='^',s=200)
    ax2.scatter(x=[1,2,3,4,5,6],y=[3,4,5,6,7,8],c=colors_,marker='^',s=200)
    plt.show()
    
  • 颜色缩写代表的颜色颜色缩写代表的颜色
    b蓝色m品红
    g绿色y黄色
    r红色k黑色
    c青色w白色

注意事项:

  • 由于默认的pyplot并不支持中文字符的显示,因此需要设置font.sans-serif参数改变绘图时的字体,使得图形可以正常显示中文。同时,由于更改字体后,会导致坐标轴中的部分字符无法显示,因此需要同时更改axes,unicode_minus参数
  • 一个棕色栗子
x = np.arange(0,1.1,0.01)
y1 = x**2
y2 = x**4

#显示中文
#注意必须在创建画布之前声明
plt.rcParams['font.sans-serif'] = 'SimHei'

#设置正常显示符号,解决保存图像中坐标轴是符号’-‘显示方块
plt.rcParams['axes.unicode_minus'] = False

#创建画布
plt.figure()

#常用设置名称
#标题
plt.title('走向图')

#x轴
plt.xlabel('x')

#y轴
plt.ylabel('y')

#x和y轴的刻度范围
plt.xlim((0,1))#范围
plt.ylim((0,1))

#刻度间距
# plt.xticks([0,0.5,1])
# plt.yticks([0,0.4,0.8,1])

#在此处加rc参数
plt.plot(x,y1,color='red',linewidth=1,linestyle=':')
plt.plot(x,y2,color='green',linewidth=2,linestyle='-.')

#图例
#注意图例要加在显示之前
plt.legend(['y=x^2','y=x^4'])

#plt.savefig('img/2.png')

plt.show()

在这里插入图片描述

2.6 图的辅助设置

ax.set_title:设置坐标系的标题
ax1.set_title('the price of materials',fontsize=14)#默认loc="center"
ax1.set_ylim:设置y坐标系的数据范围
ax1.set_ylim(0,100) 
ax1.set_xlim(0,100) #设置x坐标系的数据范围
ax1.set_ylabel:设置y坐标系的标签(指的y的含义)
ax1.set_ylabel("MAE")
ax1.set_xlabel("Epoch")#设置x坐标系的标签
ax1.set_xticks:设置x坐标系刻度的距离(指数轴的单位距离)
ax1.set_xticks(range(0,25,4)) #输入一个列表,单位距离为4.有刻度0,4,8,12,16,20,24,
ax1.set_xticklabels:设置x坐标系刻度的标签
ax1.set_xticklabels(["0h","4h","8h","12h","16h","20h","24h"])#如果不特意设置的化,默认xticks的数值

在这里插入图片描述

三、散点图(scatter diagram)

散点图时以一个特征为横坐标,另一个特征为纵坐标,利用坐标点(散点)的分布形态反应特征空间的统计关系的一种图形。

help(plt.scatter)
scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None,   
        vmin=None, vmax=None, alpha=None, linewidths=None,   
        verts=None, edgecolors=None, *, data=None, **kwargs)
x,y接受array_like,shape(n,)型数据。表示x轴和y轴对应的数据。无默认。
s接受数值或者array_like,shape(n,)型数据。指定点的大小,若传入一维array则表示每个点的大小,默认none
c接受颜色、小数、序列或者颜色数组(一维)指定点的颜色,若传入一维array则表示每个点的颜色,默认none
marker接受特定string.表示绘制的点的类型,默认为none
alpha接受0-1的小鼠。表示点的透明度。默认none
edgecolors轮廓颜色。参数与c相同
cmap色彩盘。实际为一个三列矩阵(或者array,shape(N,3),矩阵中的值取值范围为【0,1】,每一行代表一个颜色)

3.1 普通散点图

#设置数据
x=np.arange(50)/5
y=np.random.randn(50)*10
s_size=np.random.randint(1,50,50)
print(s_size)
col=[]
for i in np.arange(50):
    if s_size[i]<16:
        col.append(0)
    elif s_size[i]<34:
        col.append(1)
    else:
        col.append(2)   
print(col)

#面对对象法简单做散点图
fig,ax=plt.subplots(figsize=(8,5),dpi=80)
ax.scatter(x,y,c='blue')

#设置相关参数
ax.set_xlabel('x',fontsize=13)
ax.set_ylabel('y',fontsize=13)
ax.set_xlim(0,10)
ax.set_ylim(-10,10)
ax.set_title('The relationship of x and y',fontsize=16)
plt.show()

在这里插入图片描述

3.2 气泡图(散点图中的参数‘s_size’可以接受一维数组可以控制点的大小)

#气泡图
fig,ax=plt.subplots(figsize=(8,5),dpi=80)
ax.scatter(x,y,s=s_size*20,c='blue',alpha=0.5)

#设置相关参数
ax.set_xlabel('x',fontsize=13)
ax.set_ylabel('y',fontsize=13)
ax.set_xlim(0,10)
ax.set_ylim(-10,10)
ax.set_title('The relationship of x and y',fontsize=16)
ax.text(5,8,'bubble size is controlled by "z"')
plt.show()

在这里插入图片描述

3.3 彩点图(散点图中的‘col’中的变量用来控制点的颜色)

案例讲解

# import warnings                               #忽略警告
# warnings.filterwarnings('ignore')

#根据unique知道颜色分为3类(做个循环),挑选出i类的数据x,y,采用color[i]进行画散点图
        #for 首先要遍历所有的数据【j】,去挑选i类
               #if 如果数据【j】的颜色为i,则将对应的x数据,y数据取出来保存(创建新列表保存数据)
        #画颜色为i的散点图
#设置ax的相关属性 


fig,(ax1,ax2)=plt.subplots(1,2)

unique=list(set(col))   #颜色的分类,形成列表
colors=[plt.cm.jet(i/max(col)*0.8) for i in unique]  #生成3类四元素数表
x1.scatter(x=[1,2,3],y=[2,3,4],c=colors) 
for i in np.arange(3):
    x_=[]
    y_=[]
    for j in range(len(x)):
        if col[j]==i:
            x_.append(x[j])
            y_.append(y[j])
    ax2.scatter(x_,y_,c=colors[i]
                ,label=str(i+1)) 
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('xy_scatter')
ax2.legend()
plt.show()

在这里插入图片描述

3.4 进阶表达

# 进阶表达法
fig,ax=plt.subplots()

unique=list(set(col))
colors=[plt.cm.jet(i/max(unique)*0.8) for i in unique]    #生成3个四元素数组表示不同颜色

for i,v in enumerate(unique):
    xx=[x[j] for j in range(len(x)) if col[j]==v]
    yy=[y[j] for j in range(len(y)) if col[j]==v]
    ax.scatter(xx,yy,c=colors[i],label='Category  '+str(v))
    
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.legend(
         # loc='upper right'
         #,bbox_to_anchor=(0.5, 0.5)
          )    #众多参数性能设置。可用help功能查看
plt.show()

在这里插入图片描述

四、折线图

折线图是一种将数据点按照顺序裂解起来的图像。主要功能是查看因变量y随着自变量x改变的趋势,最适合用于显示随时间而变化的连续数据,同时还可以看出数量的的差异,增长趋势的变化。

4.1 针对线条的处理

见参考博文:《python画图线条、样式设置》

  • 常用线条参数
rc参数名称解释取值
lines.linewidth线条宽度取0-10之间的数值,默认为1.5
lines.linestyle线条样式取值有4种,默认为“-”
lines.marker线条上点的形状可取"o",“D”,“h”,"S"等20多种,默认为None
lines.markersize点的大小取0-10之间的数值,默认为1.
linestyle取值- -- -. :
意义实线长虚线点线断需线

4.2 针对数据标记的处理>

markermarkeredgecolormarkeredgewidthmarkerfacecolor
mecmewmfc
标记类型标记边界颜色标记宽度标记填充颜色
marker取值意义marker取值意义
‘o’圆圈‘.’
‘D’菱形‘S’正方形
‘h’六边形1‘*’星号
‘H’六边形2‘d’小菱形
‘-’水平线‘v’一角朝下的三角形
‘8’八边形‘<’一角超左的三角形
‘p’五边形‘>’一角朝右的三角形
‘,’像素‘^’一角朝上的三角形
‘+’加号\竖线
‘None’‘x’X

4.3 图例+网格线

#在画图时,设置参数label='',之后调用legend函数
ax.legend(fontsize=14)    #方式一,同时设置字体的大小
plt.legend()              #方式二

#plt.legend([0.1,.05])  #灵活设置图例的位置,两个0-1之间的数字表示


ax.grid(True)  #在后面添加网格线
  • legend(loc='')中的loc参数
012345
bestupper rightupper leftlower leftlower rightright
678910
center leftcenter rightlower centerupper centercenter

注意:loc的参数可以用数字来代替,以上是对应列表

plt.legend(bbox_to_anchor=(1, 1)) 
plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")
ax.legend(loc=locs[idx-1], bbox_to_anchor=(x0, y0, width, height),
            edgecolor='g', fontsize='large', framealpha=0.5,
            borderaxespad=0)
  • 两个元素

对于两个元素的bbox_to_anchor(),也就是(x,y),这个参数是代表了lengend_box的起点,并且是有后面的loc决定 的。首先明确,lengend_box是一个四边形,在这里为了方便理解将它的四条边成为:

左边,右边,顶边,底边
如,设置(0.5,0.5), loc=‘center’,那么代表lengend_box的中心点(center)坐标是(0.5, 0.5)
设置(0.5,0.5), loc=‘lower center’,那么代表底边的中点坐标是(0.5,0.5)

  • 四个元素

对于四个元素的bbox_to_anchor(),也就是(x, y, width, height),情况就和上面两个元素的有所不同了。我们通过图来展示,会更清楚一点。

  • 添加多个图例

4.4 普通折线图

#普通折线图
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

fig,ax=plt.subplots()
ax.plot(x,y,linestyle='--',linewidth=2,color='c')#cyan 缩写 c
#ax.plot(x,y,marker='o',mec='k',mfc='w',mew=0.5)#mec标记边界颜色,mfc标记填充颜色,mew标记宽度
ax.set(xlabel='x',ylabel='y',title='sin^2')
# ax.legend(loc='best') 
# ax.grid(True)

4.5. 在同一张图(axes)中画多条折线图

#一张子图(axes)画多条线
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
z=np.sin(x)

fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.plot(x,y,label='sin(x^2)')
ax.plot(x,z,label='sin(x)')
ax.plot(x,z+np.random.randn(400),label='sin(x)+error')

ax.set(xlabel='x',ylabel='y',title='Diverse sin')
ax.legend(loc='best')

在这里插入图片描述

  • 添加特定图例:如3条线添加进2条
line1,=ax.plot(x,y,label='sin(x^2)')
line2,=ax.plot(x,z,label='sin(x)')
line3,=ax.plot(x,z+np.random.randn(400),label='sin(x)+error')

ax.legend(handles=[line2,line3]  #handles句柄
         ,labels=['sin(x)','sin(x)+error'] #添加对应的标签
         )#此时只有第2条和第3条添加进图例了

在这里插入图片描述

  • 多次添加图例
ax.set(xlabel='x',ylabel='y',title='Diverse sin')
ax.legend(loc='best')
line1,=ax.plot(x,y,label='sin(x^2)')
line2,=ax.plot(x,z,label='sin(x)')
line3,=ax.plot(x,z+np.random.randn(400),label='sin(x)+error')

ax.legend(handles=[line2,line3]  #handles句柄
         ,labels=['sin(x)','sin(x)+error'] #添加对应的标签
         )#此时只有第2条和第3条添加进图例了
        
      ### 再次添加图例
leg1=ax.legend(handles=[line2,line3] ,labels=['sin(x)','sin(x)+error']) # 获得第一个图例的对象
ax.add_artist(leg1)              #把一个对象(如:line2D线条,legend图例)固定到图片中,让其成为静态
#leg1已称为静态的,再次调用legend函数
ax.legend(handles=[line1],loc='best')

在这里插入图片描述
注意到,第二次添加的图例覆盖住了第一次。在第二次添加图例的时候,将整个图看作一个新的底图。

4.6 共享x轴的subplot:twinx;同理twiny

x=np.linspace(0,10,1001)
y1=x
y2=100-x
fig,ax=plt.subplots()
ax.plot(x,y1,label='$y=x$')
ax.plot(x,y2,label='$y=100-x$')
ax.set_xlabel(r'$x$',fontsize=15)
ax.set_ylabel(r'$y$',fontsize=15)

ax.legend(loc='best')
# plt.show(

在这里插入图片描述

  • .twinx()生成一个共享x轴的subplot
fig,ax=plt.subplots(figsize=(8,5),dpi=80)
ax.plot(x,y1,label='$y=x$')
 
ax2=ax.twinx()
ax2.plot(x,y2,label=(r'$y=100-x$'))   
ax2.legend(loc='best')
ax.legend(loc='best')
plt.show
#左侧对应0-10,右侧对象90-100
#问题一:两个图例重叠了
#问题二:两条线的颜色一致
#原因在于。两条线分别隶属于不同的子图
#问题三:哪个图对应哪个坐标轴y

在这里插入图片描述

  • 修改后
fig,ax=plt.subplots()
ax.plot(x,y1,label='$y1=x$',c='C0')

ax.set_xlabel(r'$x$',fontsize=15)
#ax2.set_xlabel(r'$x$',fontsize=15)  注意到ax2对x轴的操作不显示

ax.set_ylabel(r'$y1$',fontsize=15,color='C0')      #ax中y轴标签
ax.tick_params(which='both',axis='y',colors='C0') #ax中刻度的设置(显示主刻度,对y轴操作,颜色为'C0')
#ax.spines['left'].set_color('C0')                #显示不成功,外层图为ax2

ax2=ax.twinx()                                    #创建共享x轴拥有独立y轴的supplot
ax2.plot(x,y2,label=(r'$y2=100-x$'),c='C1')       #在ax2中做线图

ax2.set_ylabel(r'$y2$',fontsize=15,color='C1')    #设置ax2的y轴标签
ax2.tick_params(which='both',axis='y',colors='C1')#设置ax2中的刻度(显示主刻度,对y轴操作。颜色为'C1')
ax2.spines['right'].set_color('C1')               #设置ax2的左轴颜色
ax2.spines['left'].set_color('C0')                #设置ax2的右轴颜色

ax2.legend(loc='center right')           #显示ax2的图例
ax.legend(loc='center left')             #显示ax1的图例
# plt.show()

在这里插入图片描述

4.7 对线图添加水平或者垂直阴影强调作用

  • 垂直阴影axvspan和水平阴影axhspan
fig=plt.figure()           #创建的是画布
ax=fig.add_subplot(1,1,1)

ax.plot(x,y2)
ax.set_xlabel(r'$x$',fontsize=15)
ax.set_ylabel(r'$y$',fontsize=15)
  • 对线图的1/4到3/4区域添加垂直阴影
fig=plt.figure()           #创建的是画布
ax=fig.add_subplot(1,1,1)

ax.plot(x,y2)
ax.set_xlabel(r'$x$',fontsize=15)
ax.set_ylabel(r'$y$',fontsize=15)

ax.axvspan(0.25,0.75,color='yellow',alpha=0.5,label='$y \leq 0$')
#ax.axhspan添加水平阴影区域

ax.legend()

在这里插入图片描述

4.8 填充两条线之间的区域

  • fill_between
#一般添加条带表示置信区间
x1=np.linspace(0.25,0.75,101)
y1=np.cos(2 * np.pi * x1)
y2=y1-0.25
fig=plt.figure()          
ax=fig.add_subplot(1,1,1)

ax.plot(x1,y1)
ax.fill_between(x1,y1,y2,color='yellow',alpha=0.5)
#ax.fill_between([0.25,0.75],y1,y2,color='yellow',alpha=0.5)
#两条线之间的区域,线是点链接成的,故要求点与点的对应
ax.set_xlabel(r'$x$',fontsize=15)
ax.set_ylabel(r'$y$',fontsize=15)
plt.show()

在这里插入图片描述

  • 一个在矩形块填充,一个在两条线之间填充
fig=plt.figure()           #创建的是画布
ax=fig.add_subplot(1,1,1)

ax.plot(x1,y1)
ax.set_xlabel(r'$x$',fontsize=15)
ax.set_ylabel(r'$y$',fontsize=15)

ax.fill_between([0.25,0.75],[-1.2,-1.2],[1.2,1.2] #是一个矩形
               ,color='yellow',alpha=0.5,label='$y \leq 0$')
#fill_between(x,y0,y1):填充y0(x) 和y1(x)之间的区域
ax.set_ylim([-1.2,1.2])     #阴影范围与坐标轴范围一致

ax.axhline(y=0,color='k',linewidth=0.5)  #添加水平线

ax.legend()

在这里插入图片描述

  • fill_betweens()fill_betweeny(自学)

4.9 填充文本

ax.text(a,b+1           #数据x,y轴位置
        ,b              #数据
        ,ha='center'   #数据的表现位置
        ,fontsize=10)  #字号大小
        
       #horizontalaligmend='center' #与文本框水平方向对齐{'center,'left','right'}
       #verticalalignment='center' #与文本框垂直方向对齐{'center','top','bottom'}
       #transform=ax.transAxes            #ax.transAxes:使用归一化坐标(传入的x,y坐标是百分比)
       #rotation=45                 #表示文本的旋转角度(逆时针)
       #bbox= dict(edgecolor='green',  #边的颜色
       #            facecolor='None' ,  #填充颜色
       #            alpha=0.5  ,         #颜色透明度
       #            linesyle-'--',       #设置线的形状
       #            linewidth=2          #设置线宽        

五、柱状图

5.1 主要参数介绍

help(plt.bar)
bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
    Make a bar plot.
--------
参数:
x:sequence of scalars(标量序列)
height : scalar or sequence of scalars   (条形高度)
width : scalar or array-like, optional    (条形宽度)
bottom : scalar or array-like, optional  (条形底部y的坐标,默认y=0)
align : {'center', 'edge'}, optional, default: 'center'  ()  
--------
其他参数:
color : scalar or array-like, optional      (条形图face的颜色)
edgecolor : scalar or array-like, optional  (条形图边的颜色) 
linewidth : scalar or array-like, optional  (线宽)  
tick_label : string or array-like, optional (条形图的标签) 
...   

5.2 创建普通的柱状图

#创建普通柱状图
#数据
data_label=list('abcde')
data_value=[30,20,15,25,10]
avg=np.mean(data_value)

#创建子图,坐标系
fig,ax=plt.subplots(figsize=(8,5),dpi=80)  #长8宽5,像素为80

ax.bar(np.arange(len(data_label)),data_value
       ,color='c'         #face of bar
       ,edgecolor='k'     #边的颜色
       ,width=0.3         #条形宽度
       ,tick_label=data_label    #条形标签
       ,align='center'             #{'center'(default),‘edge'},#跟本文框的对齐方式              
      )

#对每个条形上方添加数量
for a,b in enumerate (data_value):
    ax.text(a,b+1           #数据x,y轴位置
            ,b              #数据
            ,ha='center'   #数据的表现位置
            ,fontsize=10)  #字号大小
    

#对axis设置标题+y轴范围
ax.set_title('the price of materials'          #设置标题(材料价格)
            ,fontsize=14)                    
ax.set_ylim(0,35) 

在这里插入图片描述

5.3 对axis的一些设置

#添加水平线axhline
#添加垂直线axvline
#添加一条平均线,表示材料的平均价格
ax.axhline(y=avg
           ,color=(210/255,199/255,180/255)
          ,linestyle='--')
ax.text(len(data_label),avg+1
       ,'average is :'+str(int(avg))) 
       
#添加一个箭头
ax.arrow(0,32,4,-8     #箭头从(0,32)到(0+4,32-8)的位置     
         ,alpha=0.5
         ,width=0.1
        ,shape='right'
        ,linestyle='--'
        ,color='orange' ) 
  
#对axis的设置去除边框线,去掉y轴刻度
ax.spines['left'].set_color('none')   #ax.spines?是一个字典axis的四个边
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#ax.spines['bottom'].set_color('none')
ax.set_yticks([])

在这里插入图片描述

5.4 堆积柱状图

#堆积柱状图
#8,9月份有售出1号,2号,3号,4号,5号,5种类型的衣服,查看两个月每种型号各卖出多少

#显示中文
#注意必须在创建画布之前声明
plt.rcParams['font.sans-serif'] = 'SimHei'

#设置正常显示符号,解决保存图像中坐标轴是符号’-‘显示方块
plt.rcParams['axes.unicode_minus'] = False

sales8=[10,20,30,15,18]
sales9=[10,12,24,32,8]

labels=['{}号衣服'.format(i) for i in range(1,6)]

fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.bar(np.arange(len(sales8)),sales8,tick_label=labels,label='8 月')
ax.bar(np.arange(len(sales9)),sales9,tick_label=labels,label='9 月',bottom=sales8)

ax.legend()

在这里插入图片描述

5.5 并列柱状图

#并列柱状图
#显示中文
#注意必须在创建画布之前声明
plt.rcParams['font.sans-serif'] = 'SimHei'

#设置正常显示符号,解决保存图像中坐标轴是符号’-‘显示方块
plt.rcParams['axes.unicode_minus'] = False

sales8=[10,20,30,15,18]
sales9=[10,12,24,32,8]

labels=['{}号衣服'.format(i) for i in range(1,6)]

#plt.style.use('bmh')
#plt.style.use('ggplot')
fig,ax=plt.subplots(figsize=(8,5),dpi=80)

width_=0.4   #当偏移值与宽度一致时,两个柱子就会紧贴在一起
ax.bar(np.arange(len(sales8))       ,sales8,width=width_,tick_label=labels,label='8 月')
ax.bar(np.arange(len(sales9))+width_ ,sales9,width=width_,tick_label=labels,label='9 月')

ax.legend()

在这里插入图片描述

5.6 使用风格

plt.style.available        #查看风格
plt.style.use('ggplot')    #使用风格

5.7 复合要求的举例:并列+水平线+文字+紧图保存

MAE = [[50.73, 51.43,54.43],
       [45.94, 49.49,47.28],
       [50.04,45.43,42.40]]
RMSE=[[25.4, 26.22, 22.51],
     [21.69,26.04, 20.11],
     [22.12,22.71,23.33]] 
X_tick=['STRPA-A','STRPA-C','STRPA']  
labels=["Morning","Noon","Evening"]  
fig,(ax1,ax2)=plt.subplots(1,2,figsize=(16,5),dpi=80)
 

ax1.set_ylim([0,80]) #设置Y轴坐标范围
width_=0.2   #当偏移值与宽度一致时,两个柱子就会紧贴在一起
for i in range(len(MAE)):
    ax1.bar(np.arange(3)+i*width_, MAE[i], width=width_,label=labels[i])
ax1.set_xticks(np.arange(width_,2.5,1)) #输入一个刻度的列表
ax1.set_xticklabels(X_tick)    #对刻度改标签 
ax1.axhline(y=np.mean(MAE),color=(210/255,199/255,180/255) ,linestyle='--')
for i in range(3):
    for a,b in enumerate (MAE[i]):
        ax1.text(a+i*width_,b+1 ,b ,ha='center',fontsize=10)  
ax1.legend()  

 
ax2.set_ylim([0,35])
ax2.bar(np.arange(3)       ,RMSE[0],width=width_,label='Morning')
ax2.bar(np.arange(3)+width_ ,RMSE[1],width=width_,tick_label=X_tick,label='Noon')
ax2.bar(np.arange(3)+2*width_ ,RMSE[2],width=width_,label='Evening')
ax2.axhline(y=np.mean(RMSE),color=(210/255,199/255,180/255),linestyle='--')
for i in range(3):
    for a,b in enumerate (RMSE[i]):
        ax2.text(a+i*width_,b+1           #数据x,y轴位置
                ,b              #数据
                ,ha='center'   #数据的表现位置
                ,fontsize=10)  #字号大小
ax2.legend()   
plt.savefig("MAEandRMSE.png",bbox_inches='tight')  #保存的时候不要留旁边的空白   

在这里插入图片描述

六、条形图

6.1 主要参数介绍

help(plt.barh)
barh(y, width, height=0.8, left=None, *, align='center', **kwargs)
    Make a horizontal bar plot.
--------
y : scalar or array-like          (条形图的y轴坐标)
width : scalar or array-like     (条形图的宽度)
height : sequence of scalars, optional, default: 0.8  (条形图的高度,默认0.8)
left : sequence of scalars   (标量序列,条形图左边x轴的坐标,默认为0)
align : {'center', 'edge'}, optional, default: 'center'
--------
color : scalar or array-like, optional  (条形图的颜色)
edgecolor : scalar or array-like, optional  (条形图的边的颜色)
linewidth : scalar or array-like, optional   (条形图边的宽度) 
tick_label : string or array-like, optional   (条形图的标签,默认none)   
 ... 

6.2 普通条形图

  • 创造数据
data={'station':np.arange(11001,11011),
     'borrow':[62,23,25,13,9,7,21,13,9,11],
     'return':[41,38,16,24,31,40,20,7,15,4],
     'total':[35,32,38,30,37,29,42,39,28,48]}
data=pd.DataFrame(data)
data    #查看dataFrame数据

data['station']  #取一列  series
  • 作图
#条形图
#y轴坐标
y_station=np.arange(len(data['station']))

#x轴坐标
x_total=data['total']

#y轴刻度标签
y_labels=['sttion {}'.format(i)  for i in data['station']]

fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.barh(y_station , x_total , tick_label=y_labels) 

#设置axis
ax.set_xlabel('total number ')
ax.set_title('total number of bicycles on these station')

#添加数据标签
for a,b in enumerate(x_total):
    ax.text(b+2,a,    #添加位置
           b          #添加数据
           ,ha='center')#居中

在这里插入图片描述

发现条形图比较散乱,希望能够排序一下,方便观察特征。故,事先将数据排序。
数据先排序,后作图

data=data.sort_values(by=['total']
                   #,ascending=False
                  )
data

在这里插入图片描述

6.3 .旋风图(正负条形图)

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
data=data.sort_values(by=['station'])

#y轴坐标
y_station=np.arange(len(data['station']))

#x轴坐标
x_borrow=data['borrow']
x_return=data['return']

#y轴刻度标签
y_labels=['sttion {}'.format(i)  for i in data['station']]

fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.barh(y_station , x_borrow , label='borrow' , tick_label=y_labels , height=0.5)
ax.barh(y_station , -x_return , label='return' , tick_label=y_labels , height=0.5)

#设置axis
ax.set(xlabel='自行车使用数量',ylabel='站点编号',title='10个站点的自行车使用情况')
ax.set_xlim(-100,100)
ax.legend()

#添加数据标签
for b,a in enumerate(x_borrow): #b时y轴,a是x轴
    ax.text(a+2,b
           ,a
           ,ha='center'
           ,fontsize=10)
for b,a in enumerate(x_return): #b时y轴,a是x轴
    ax.text(-a-2,b
           ,a
           ,ha='center'
           ,fontsize=10)

在这里插入图片描述

七、直方图

又称质量分布图,由一系列高度不等的纵向条纹或线段表示数据分布的情况,一般用横轴表示数据所属类型,纵轴表示数量或者占比。

7.1 简单作图

help(ax.hist)
hist(x, bins=None, range=None, density=None, weights=None, cumulative=False,
     bottom=None, histtype='bar', align='mid', orientation='vertical', 
     rwidth=None, log=False, color=None, label=None, stacked=False,
     normed=None, *, data=None, **kwargs) 
返回一个直方图
fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.hist(data['total'])

八、饼图

8.1 参数介绍

help(plt.pie)
pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, 
    shadow=False, labeldistance=1.1, startangle=None, radius=None, 
    counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), 
    frame=False, rotatelabels=False, *, data=None)
    Plot a pie chart
------------
x : array-like (扇形尺寸)
explode : array-like, optional, default: None(表示指定项离饼图圆心为n个半径)
labels : list, optional, default: None    (扇形标签)
colors : array-like, optional, default: None    
autopct : None (default), string, or function, optional(设置文本格式)  
pctdistance : float, optional, default: 0.6  (百分比数据距离圆心的位置)
shadow : bool, optional, default: False      (在饼图下面画阴影)  
labeldistance : float or None, optional, default: 1.1 (绘制饼图标签的径向距离,即距离圆心多少个半径)
startangle : float, optional, default: None (第一块扇形的起始角度)         
radius : float, optional, default: None  (设置饼图的半径,默认情况为1)  
counterclock : bool, optional, default: True (指定方向,顺时针或者逆时针(默认))  
frame : bool, optional, default: False   (True,绘制坐标图的框架)  
... 

8.2 画一个饼图

fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.pie(data['total']               #数据
      ,labels=data['station']      #标签
      ,startangle=90               #起始角
      ,autopct='%.f%%'             #百分比格式
      ,pctdistance=0.3             #百分比位置
      )
ax.tick_params(top='off')         #显示最后的代码内容      

在这里插入图片描述

九、箱线图

也称箱须图,其绘制需使用常用的统计量,能够提供有关数据位置和分散情况的关键信息,尤其在比较不同特征时,更课表现其分散程度差异。

箱线图利用数据中的五个统计两(最小值、下四分位数、中位数、上四分位数和最大值)来描述数据,它可以粗略的看书数据是否具有对称性、分布的分散程度等信息,特比可以用于对几个样本的比较。
在这里插入图片描述
鸢尾花数据了解

#导入数据并加载
from sklearn.datasets import load_iris
iris=load_iris()
  • 查看数据板块
    dir(iris)
    #结果:[‘DESCR’, ‘data’, ‘feature_names’, ‘filename’, ‘target’, ‘target_names’]

  • 查看数据
    iris.data
    iris.target
    iris.target_name
    iris.feature_names

  • 创建DataFarme数据

iris_data=pd.DataFrame(iris.data,columns=iris.feature_names) #数据,列名
iris_target=pd.DataFrame(iris.target,columns=['target'])

datas=pd.concat([iris_data,iris_target],axis=1)      #特征数据与标签数据合二为一
  • 按标签分组选择数据

iris_target['target'].value_counts()    #计算出现的元素的频次 
#取巧似数据分割
data_setosa=datas.loc[:50]
data_versicolor=data.loc[50:100]
data_virginica=data.loc[100:150]

9.1 主要参数介绍

help(plt.boxplot)
boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None,widths=None, patch_artist=None,          bootstrap=None, usermedians=None,  conf_intervals=None, meanline=None, showmeans=None, showcaps=None,     showbox=None, showfliers=None, boxprops=None, labels=None,   flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, *, data=None)
    Make a box and whisker plot.
-------------------  
x: Array or a sequence of vectors  (输入数据,向量序列或者数组)
notch : bool, optional (False)  (表示中间箱体是否有缺口,缺口代表中位数附件的置信区间)
sym : str, optional   (接受特定字符串,指定异常点的形状,none 默认'b+',不想显示异常点,则设置字符串为空) 
vert : bool, optional (True)   (表示箱体的横纵方向。True,垂直的;False,水平的)
positions : array-like, optional (设置箱体的位置,默认为range(1,N+1),N为箱体的个数)
widths : scalar or array-like  (设置箱体的宽度,默认为0.5)
labels : sequence, optional   (每个数据集的标签,注意长度与x的尺寸相同)   
meanline : bool, optional (False) (显示均值线,if True与showmeans=True一致)    
 ...   

9.2 画一个箱体

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.boxplot(data_setosa['sepal length (cm)']
          ,showmeans=True                       #显示中位线
           ,notch=True                          #显示中位线附件缺口
           ,labels=['sepal length of setosa']   #设置箱体的标签
          )
data_setosa['sepal length (cm)'].describe().round(2)

在这里插入图片描述

9.3 画多个箱体

#设置数据集
setosa=[data_setosa['sepal length (cm)'],data_setosa['sepal width (cm)'] ,\
        data_setosa['petal length (cm)'],data_setosa['petal width (cm)']]
labels=['{} of setosa'.format(x) for x in iris.feature_names]
  • 作图
fig,ax=plt.subplots(figsize=(8,5),dpi=80)

ax.boxplot(setosa,labels=labels)
ax.tick_params(top='off')     #显示最后的代码内容

在这里插入图片描述

#编历Dataframe的列
setosa=[]
for index in data_setosa.columns:
    setosa.append(data_setosa[index])
setosa[1]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值