关于机器学习:python绘图常用知识

27次阅读

共计 4625 个字符,预计需要花费 12 分钟才能阅读完成。

python 绘图罕用常识

figure()、subplot()和 subplots()、figure.add_subplot()、figure.add_axes()、plt.plot()、plt.xlim()和 plt.ylim()、plt.legeng()、plt.show()

figure()函数

函数原型:

matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)

— Create a new figure, or activate an existing figure. 新建一个画布或者激活一个曾经存在的画布

参数:

  • num: int or str, figure 的惟一编号。不指定调用 figure 时就会默认从 1 减少主动传入 int。
  • figsize: 指定 figure 的宽和高,单位为英寸;=(weight,height)
  • dpi: 指定绘图对象的分辨率,即每英寸多少个像素,缺省值为 80 1 英寸等于 2.5cm,A4 纸是 21*30cm 的纸张
  • facecolor: 背景色彩,facecolor=’blue’
  • edgecolor: 边框色彩
  • frameon: 是否显示边框

(1)对于只画一张图,能够不应用plt.figure(),会默认将图形画在一张画布中

import matplotlib.pyplot as plt
x=[1,2,3]
y1=[1,2,4]
y2=[1,4,8]
plt.plot(x,y1,color = "red",label = "red")
plt.plot(x,y2,color = "green",label = "green")
plt.legend()  #无此语句会不显示右上角 label
plt.show()

(2)如果想画两张图则必须应用 plt.figure() 两次, 能够指定 num,也能够不指定 num,调用两次它会默认加 1

import matplotlib.pyplot as plt
x=[1,2,3]
y1=[1,2,4]
y2=[1,4,8]

plt.figure()
plt.plot(x,y1,color = "red",label = "red")
plt.legend()  #无此语句会不显示右下角 label

plt.figure()
plt.plot(x,y2,color = "green",label = "green")
plt.legend()  #无此语句会不显示右上角 label
plt.show()

当然你也能够指定同一个 num,他会和下面的输入后果统一,在同一张画布中输入图像

这个也就提供了咱们后续向某个画布中增加图像的机会,只须要调用 plt.figure(num),而后调用绘制图形的函数即可,比方plt.plot() 等。

subplot()和 subplots()

subplot()能够将 figure 划分为 n 个子图,而后每次执行一次 subplot()会生成一个对应地位的子图

subplot()函数原型:

subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)`

参数:

  • nrows: subplot 的行数
  • ncols:subplot 的列数
  • sharex:所有 subplot 应该应用雷同的 X 轴刻度(调节 xlim 将会影响所有的 subplot)
  • sharey: 所有 subplot 应该应用雷同的 Y 轴刻度(调节 ylim 将会影响所有的 subplot)
  • subplot_kw: 用于创立各 subplot 的关键字字典
  • **fig_kw: 创立 figure 时的其余关键字
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#作图 1
plt.subplot(2,2,1)  #等效于 plt.subplot(221)
plt.plot(x, x)
#作图 2
plt.subplot(2,2,2)
plt.plot(x, -x)
#作图 3
plt.subplot(2,2,3)
plt.plot(x, x ** 2)
plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图 4
#plt.subplot(224)
#plt.plot(x, np.log(x))
plt.show()

subplots()函数与 subplot()参数类似

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 100)
#划分子图
fig,axes=plt.subplots(2,2)   #返回一个画布和画轴对象,能够取出对于的画轴而后调用绘图函数
ax1=axes[0,0]
ax2=axes[0,1]
ax3=axes[1,0]
ax4=axes[1,1]

#作图 1
ax1.plot(x, x)
#作图 2
ax2.plot(x, -x)
#作图 3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图 4
#ax4.plot(x, np.log(x))
plt.show()

和 subplot()不同的是,subplots()一次画出所有的画轴,而后再调用绘图函数

figure 对象能够增加子图或绘图区域

figure.add_subplot()

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#新建 figure 对象
fig=plt.figure()
#新建子图 1
ax1=fig.add_subplot(2,2,1)
ax1.plot(x, x)
#新建子图 3
ax3=fig.add_subplot(2,2,3)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#新建子图 4
ax4=fig.add_subplot(2,2,4)
ax4.plot(x, np.log(x))
plt.show()

能够看出和 subplot 的成果没什么不同

figure.add_axes()

import numpy as np
import matplotlib.pyplot as plt

#新建 figure
fig = plt.figure()
# 定义数据

x = np.array([1, 2, 3, 4, 5, 6, 7])

#新建区域 ax1

#figure 的百分比, 从 figure 10% 的地位开始绘制, 宽高是 figure 的 80%
#图像还是要在 figure 外部

left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# 取得绘制的句柄
ax1 = fig.add_axes([left, bottom, width, height])  #获取一个区域
ax1.plot(x,x**2 , 'r')
ax1.set_title('a1')
#plt.plot(x, y, 'r')

#新增区域 ax2, 嵌套在 ax1 内
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
# 取得绘制的句柄
ax2 = fig.add_axes([left, bottom, width, height])# 获取另一个区域
ax2.plot(x,x**3, 'b')
ax2.set_title('a2')
plt.show()

这样就能够在 figure 的任何中央绘制图像,更加灵便!

plt.plot()

参数:

  • x, y : x 是可选的,如果 x 没有,将默认是从 0 到 n -1,也就是 y 的索引。
  • fmt : str, optional, 定义线条的色彩和款式的操作,如“ro”就是红色的圆圈, “r–“ 就是红色虚线,这是一个疾速设置款式的办法,更多的参数能够参考最初一个 keyboard arguments。
  • kwargs : Line2D properties, optional 这是一大堆可选内容,能够来外面指定很多内容,如“label”指定线条的标签,“linewidth”指定线条的宽度,等等
import matplotlib.pyplot as plt

a = [1, 2, 3, 4] # y 是 a 的值,x 是各个元素的索引
b = [5, 6, 7, 8]

plt.plot(a, b, 'g--', label = 'aa')
plt.xlabel('this is x')
plt.ylabel('this is y')
plt.title('this is a demo')
plt.legend() # 将样例显示进去
plt.show()

plt.xlim()和 plt.ylim()

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,10,1000)
y = np.random.rand(1000)

plt.scatter(x,y,label="scatter figure")
plt.legend()

plt.xlim(1,10) #指定 x 和 y 的刻度值
plt.ylim(0,1)
plt.show()

plt.legeng()

legend——–(翻译:(地图或图标)图例、阐明、解释)

1.设置图列地位

plt.legend(loc='')#  填入地位,如:upper left, 则图例在左上角

2.设置图例字体大小

fontsize : int or float or {‘xx-small’,‘x-small’,‘small’,‘medium’,‘large’,‘x-large’,‘xx-large’}

3.设置图例边框及背景

plt.legend(loc='best',frameon=False) #去掉图例边框
plt.legend(loc='best',edgecolor='red') #设置图例边框色彩
plt.legend(loc='best',facecolor='blue') #设置图例背景色彩, 若无边框, 参数有效

4.设置图例题目

legend = plt.legend(["BJ", "SH"], title='Beijing VS Shanghai')
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10,1)
plt.plot(x,x,'r--',x,np.cos(x),'g--',marker='*')
plt.xlabel('row')
plt.ylabel('cow')
plt.legend(["BJ","SH"],loc='upper left',title='Beijing VS Shanghai'
         # ,frameon=False
          ,edgecolor='green'
          ,facecolor='black')
plt.show()

plt.show()

plt.show()是显示图片,对于有人说为什么我没有应用此函数,一样能够显示图片??

那可能是你在应用 IPython 这一类的交互式编程环境,比方jupyter notebook 也属于外部就是调用了IPython,因为这一类能够及时输入后果,如果你是要 IDE(集成开发环境,如 pycharm),就必须应用plt.show()

正文完
 0