python中 Matplotlib学习笔记

注:本文章主要是对之前在CSDN上学习的一篇matplotlab文章中的内容进行一个简单整理,主要目的是深化自己的记忆。

原文章请见后面链接:原文章链接

Matplotlib

Matplotlib 是python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib,它以各种硬拷贝格式和跨平台的交互式环境出版生成质量级别的图形,它能输出的图形包括折线图,散点图,直方图等,在数据可视化方面,matplotlib拥有数量众多的忠实用户,其强悍的绘图能力能够帮助我们对数据形成非常清晰直观的认知。

1.认识 Matplotlib

1.1 Figure

在任何绘图之前,我们需要一个Figure对象,可以理解成我们需要一张画板才能开始绘图。

import matplotlib.pyplot as plt
f=plt.figure()

1.2 Axes

在拥有Figure对象之后,在作画前我们还需要轴,没有轴的话就没有绘图基准,所以需要添加Axes。也可以理解成为真正可以作画的纸。

import matplotlib.pyplot as plt
f=plt.figure()
ax=f.add_subplot(111)
ax.set(xlim=[0.5,4.5],ylim=[-2,8],title='An Example Axes',ylabel='Y-Axis',xlabel='X-Axis')
plt.show()

上的代码,在一幅图上添加了一个Axes,然后设置了这个Axes的X轴以及Y轴的取值范围(这些设置并不是强制的,后面会再谈到关于这些设置),效果如下图:
在这里插入图片描述
对于上面的fig.add_subplot(111)就是添加Axes的,参数的解释的在画板的第1行第1列的第一个位置生成一个Axes对象来准备作画。也可以通过fig.add_subplot(2, 2, 1)的方式生成Axes,前面两个参数确定了面板的划分,例如 2, 2会将整个面板划分成 2 * 2 的方格,第三个参数取值范围是 [1, 2*2] 表示第几个Axes。如下面的例子:

import matplotlib.pyplot as plt
f=plt.figure()
ax1=f.add_subplot(221)
ax2=f.add_subplot(222)
ax3=f.add_subplot(224)
plt.show()

在这里插入图片描述

Multiple Axes

可以发现我们上面添加 Axes 似乎有点弱鸡,所以提供了下面的方式一次性生成所有 Axes:

import matplotlib.pyplot as plt
f, axes = plt.subplots(nrows=2, ncols=2)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right')
plt.show()

在这里插入图片描述

2. 基本绘图2D

2.1 线

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x=np.linspace(0,np.pi)
y_sin=np.sin(x)
y_cos=np.cos(x)
ax1=plt.plot(x,y_sin)
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x=np.linspace(0,np.pi)
y_sin=np.sin(x)
y_cos=np.cos(x)
ax2=plt.plot(x,y_sin,'go--',linewidth=2,markersize=12)
plt.show()

在这里插入图片描述

2.2 散点图

import matplotlib.pyplot as plt
import numpy as np
x=np.arange(10)
y=np.random.randn(10)
plt.scatter(x,y,color='red')
plt.show()

在这里插入图片描述

2.3 条形图

条形图分两种,一种是水平的,一种是垂直的,见下例子:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
x = np.arange(5)
y = np.random.randn(5)

fig, axes = plt.subplots(ncols=2, figsize=plt.figaspect(1./2))

vert_bars = axes[0].bar(x, y, color='lightblue', align='center')
horiz_bars = axes[1].barh(x, y, color='lightblue', align='center')
axes[0].axhline(0, color='gray', linewidth=2)
axes[1].axvline(0, color='gray', linewidth=2)
plt.show()

在这里插入图片描述
条形图还返回了一个Artists 数组,对应着每个条形,例如上图 Artists 数组的大小为5,我们可以通过这些 Artists 对条形图的样式进行更改,如下例:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.random.randn(5)
fig, ax = plt.subplots()
vert_bars = ax.bar(x, y, color='lightblue', align='center')
for bar, height in zip(vert_bars, y):
    if height < 0:
        bar.set(edgecolor='darkred', color='salmon', linewidth=3)

plt.show()

在这里插入图片描述

2.4 直方图

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
ax1.hist(x, n_bins, density=True, histtype='barstacked')
ax1.set_title('stacked bar')
ax2.hist(x,  histtype='barstacked', rwidth=0.9)
ax3.hist(x[:, 0], rwidth=0.9)
ax3.set_title('different sample sizes')
fig.tight_layout()
plt.show()

在这里插入图片描述
参数中density控制Y轴是概率还是数量,与返回的第一个的变量对应。histtype控制着直方图的样式,默认是 ‘bar’,对于多个条形时就相邻的方式呈现如子图1, ‘barstacked’ 就是叠在一起,如子图2、3。 rwidth 控制着宽度,这样可以空出一些间隙,比较图2、3. 图4是只有一条数据时。

2.5 饼图

import matplotlib.pyplot as plt
import numpy as np
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
fig1, (ax1, ax2) = plt.subplots(2)
ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True)
ax1.axis('equal')
ax2.pie(sizes, autopct='%1.2f%%', shadow=True, startangle=90, explode=explode,
    pctdistance=1.12)
ax2.axis('equal')
ax2.legend(labels=labels, loc='upper right')
plt.show()

在这里插入图片描述
饼图自动根据数据的百分比画饼.。labels是各个块的标签,如子图一。autopct=%1.1f%%表示格式化百分比精确输出,explode,突出某些块,不同的值突出的效果不一样。pctdistance=1.12百分比距离圆心的距离,默认是0.6.

2.6 箱型图

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(100)
data=np.random.normal(size=(1000,4),loc=0,scale=1) 
labels=['A','B','C','D']
plt.boxplot(data,labels=labels)
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值