1.初步了解画图
# matplotlib
import matplotlib.pylab as plt
import numpy as np
# 设置绘图风格
plt.style.use('classic')
# print(plt.style.available)
# 设置字体,以便显示中文
plt.rcParams['font.sans-serif'] = ['FangSong']
# 1.创建画布
fig = plt.figure()
# 设置画布大小
fig.set_size_inches(10,10)
fig.set_facecolor('pink')
# 创建子图位置
sumb = fig.add_axes([0.1,0.1,0.5,0.5])
#设置数据
x = np.linspace(-10,10,20)
y = np.power(x,3)
y1 = x * x
# print(x,y,y1)
# 画线
sumb.plot(x,y,color = 'blue',linestyle = '-.',linewidth = 3,label = '$x ^ 3$')
sumb.plot(x,y1,color = 'red',linestyle = ':',linewidth = 5,label = '$x ^ 10$')
#添加文本的标志
sumb.text(2,5,r'$x^3$',fontsize=10)
sumb.text(2,300,r'$x^10$',fontsize=10)
# 图例
sumb.legend(loc = "upper left")
# 设置x,y的标志
sumb.set_xlabel('x轴',fontdict={'size':12})
sumb.set_ylabel('y轴', fontdict={'size': 14})
# 显示
plt.show()
显示结果为:(发现负号没有显示)
画图的分块
import matplotlib.pylab as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['FangSong']
x = np.linspace(0,10,20)
y = np.power(x,3)
y1 = x*10
#图1的位置
#一行两列中的第一个
plt.subplot(1,2,1)
plt.title('图例一')
plt.plot(x,y,color = 'red',ls = '--',linewidth = 5)
#图2的位置
#一行两列中的第二个
plt.subplot(1,2,2)
plt.title('图例二')
plt.plot(x,y1,color ='blue',ls = ':',linewidth = 5)
2.各类图像
1.折线图
#折线图,画出一元二次方程函数的图为例子
import matplotlib.pylab as plt
import numpy as np
x = np.linspace(-10,10,20)
y = np.power(x,2)
#折线图参数(color颜色,marker折点的图形,markersize尺寸,linestyle(ls),折线的样式,linewidth的宽度)
plt.plot(x,y,color = 'red',marker = '*',markersize = 3,ls = ':',linewidth = 5)
plt.show()
图像如下:
2.柱状图
import matplotlib.pylab as plt
plt.rcParams['font.sans-serif'] = ['FangSong']
x = ['A','B','C','D']
y = [1,2,5,3]
fig,(ax1,ax2) = plt.subplots(1,2,figsize=(12,5))
#水平柱状图
ax1.bar(x,y,color = 'red')
ax1.set_title('第一个图')
ax1.set_xlabel('横坐标')
ax1.set_ylabel('纵坐标')
#垂直柱状图
ax2.barh(x,y,color = 'blue')
ax2.set_title('第二个图')
ax2.set_xlabel('横坐标')
ax2.set_ylabel('纵坐标')
plt.show()
图像结果为
3.折线图
#饼图
import matplotlib.pylab as plt
plt.rcParams['font.sans-serif'] = ['FangSong']
x = ['A','B','C','D']
y = [15,25,50,10]
#图一,参数(数值,名字labels,颜色设置colors,autopct(可以设置显示百分比),startangle(设置开始角度))
# plt.pie(y,labels = x,colors=['r','g','b','pink'],autopct='%1.1f%%',startangle=0)
#图二pctdistance每个饼片的中心与由autopct生成的文本的开头之间距离与半径的比率,大于1的话会显示在圆外
#图三explode可以显示每片饼突出的程度
# 图四显示阴影shadow
plt.pie(y,labels = x,colors=['r','g','b','pink'],autopct='%1.1f%%',startangle=0,pctdistance=0.6,
explode =[0.2,0,0,0] shadow = True)
plt.show()
图一:
图二:
图三:
图四:
4.散点图
# 散点图
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['FangSong']
# 显示正确的符号
plt.rcParams['axes.unicode_minus'] = False
#randn符合正态分布的-1.96到+1.96
x = np.random.randn(50)
y = np.random.randn(50)
#设置随机颜色,颜色映射
color = np.random.rand(50)*10
#设置随机大小
area = np.square(np.random.rand(50)*25)
plt.scatter(x,y,c = color,s = area)
plt.title('散点图')
plt.xlabel("横轴")
plt.ylabel("纵轴")
plt.show()
代码为E1_4
图为: