介绍:
Matplotlib是一个用于创建2D图表和绘图的Python库。它提供了广泛的功能,可以用于生成各种类型的图表,包括线图、散点图、条形图、直方图、饼图等等。Matplotlib可以用于数据可视化、数据分析、数据探索和科学计算。
Matplotlib的主要特点包括:
-
易于使用:Matplotlib提供了简单直观的API,使得绘制图表变得简单。用户可以通过简单的几行代码就能够创建出复杂的图表。
-
高度可定制性:Matplotlib允许用户对图表的各个方面进行高度自定义,包括图像样式、颜色、坐标轴设置等等。
-
多种输出格式:Matplotlib可以将图表导出为多种格式,包括图片格式如PNG、JPG、SVG等,以及PDF、SVG和EPS等矢量格式。
-
支持Jupyter Notebook:Matplotlib可以很好地与Jupyter Notebook集成,方便在Notebook环境下创建和展示图表。
使用Matplotlib,您可以创建各种类型的图表,例如:
-
线图:用于表示连续数据之间的关系。
-
散点图:用于表示两组数据之间的关系,每一对数据被表示为一个点。
-
条形图:用于比较不同类别的数据。
-
直方图:用于显示数据的频率分布。
-
饼图:用于显示部分与整体的关系。
python
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False#用来正常显示负号
%matplotlib inline
一、散点图
python
import numpy as np
x=np.arange(0,10)
y=np.arange(11,21)
plt.scatter(x,y,c='b')#散点图,c参数为颜色

python
plt.scatter(x,y,c='r')#散点图

python
a=np.arange(40,50)
b=np.arange(50,60)
plt.scatter(x,y,c='g')
plt.xlabel('x轴坐标中文显示')
plt.ylabel('y轴坐标中文显示')
plt.title('标题显示')
plt.savefig('Test.png')#保存图片

二、线图
python
y=x*x
plt.plot(x,y,'ro',linestyle='solid',linewidth=1,markersize=8)#linestyle 线的类型 linewidth 线的宽度,markersize 点的大小
plt.xlabel('x轴坐标中文显示')
plt.ylabel('y轴坐标中文显示')
plt.title('标题显示')
y=x*x
plt.plot(x,y,'gx',linestyle='solid',linewidth=1,markersize=8)
plt.xlabel('x轴坐标中文显示')
plt.ylabel('y轴坐标中文显示')
plt.title('标题显示')


python
plt.subplot(2,2,1)#两行两列第一个图
plt.plot(x,y,'gx')#线图
plt.subplot(2,2,2)#两行两列第二个图
plt.plot(x,y,'ro')#线图
plt.subplot(2,2,3)#两行两列第三个图
plt.plot(x,y,'b--')#线图
plt.subplot(2,2,4)#两行两列第四个图
plt.plot(x,y,'y*')#线图

python
x=np.arange(1,11)
y=3*x+5
plt.xlabel('x轴坐标中文显示')
plt.ylabel('y轴坐标中文显示')
plt.title('标题显示')
plt.plot(x,y)

python
x=np.arange(0,4*np.pi,0.1)
y=np.sin(x)
plt.title("sine wave form")
plt.plot(x,y)

python
x=np.arange(0,4*np.pi,0.1)
y_sin=np.sin(x)
y_cos=np.cos(x)
plt.subplot(2,1,1)
plt.plot(x,y_sin,'r--')
plt.title("sine")
plt.subplot(2,1,2)
plt.plot(x,y_cos,'g--')
plt.title("cosine")

三、条形图
python
x=[2,8,10]
y=[11,16,9]
x2=[3,9,11]
y2=[6,15,7]
plt.bar(x,y)#柱状图,默认蓝色
plt.bar(x2,y2,color='g')

四、直方图
python
a=np.array([1,2,3,4,5,6,7,8,5,4,2,9,10,2,7,7,7,7,9])#直方图
plt.hist(a,bins=20)#20之内,出现的次数

五、盒图
python
data=[np.random.normal(0,std,100) for std in range(1,4)]#0到1随机100个,0到2随机100个,0到3随机100个
plt.boxplot(data,vert=True,patch_artist=False)#盒图

六、饼图
python
labels='python','C++','ruby','java'#标题
sizes=[215,160,245,210]#数据
colors=['gold','yellowgreen','lightcoral','lightskyblue']#颜色
explode=(0.1,0.1,0,0)#分离度
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct="%1.1f%%",shadow=False)
#autopct 百分比 保留几位 shadow阴影
plt.axis('equal')

python
labels='python','C++','ruby','java'#标题
sizes=[215,160,245,210]#数据
colors=['gold','yellowgreen','lightcoral','lightskyblue']#颜色
explode=(0.1,0.1,0,0)#分离度
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct="%1.1f%%",shadow=True)
#autopct 百分比 保留几位 shadow阴影
plt.axis('equal')
