Python matplotlib (2D graphics library) 1

matplotlib Profile

matplotlib is the most famous drawing python library that provides a set of command and matlab similar API, to be very suitable for interactive mapping. But it may also be convenient to control as the drawing, the embedded GUI applications. It is fairly complete documentation, and the Gallery page, there are hundreds of thumbnails, and then have to open source. So if you need to draw some type of chart, only browse / copy / paste it on this page, basically can get.

In the relatively well-known Linux data mapping tool also gnuplot, this is free, Python has a packet can call gnuplot, but the syntax is not used, and drawing quality is not high. The Matplotlib is relatively strong: Matlab syntax, python language, quality latex paint (you can also use mathematical formulas embedded latex engine drawn).

Matplotlib parts of the image
(1) Figure: Figure entire image of a subject. Figure object may comprise a one or more sub-Axes FIG.

(2) Axes: Each Axes (ax) has a drawing area of the object is its own coordinate system. Axes can subgraphs the subplot () fast rendering.
Each object can be carded following relationship:
the image all objects are derived from the base class Artist.

And subpicture current profile may be used plt.gcf () and plt.gca () is obtained, and represent the Get Current Figure Get Current Axes.

matplotlib.pyplot
matplotlib.pyplot (hereinafter abbreviated as PLT) is a set of command-line style functions, so matplotlib MATLAB similar manner to work. Each plt function to do a picture (figure) some changes: for example, create new images, create a new mapping area (plotting area) in the picture, draw a straight line in the plot area, add a label (label) to diagrams . plt is the state, that it will save the current state of the picture and the mapping of the area, a new mapping function in the role of the state on the basis of the current picture.

Some modifications may be made plt on picture follows:
(. 1) plt.axis: axis

plt.axis ([0,6,0,20])
Axis () function takes the form [xmin, xmax, ymin, ymax ] parameter specifies the X, Y-axis coordinate range.

(2) Tick: tick, Tick Label: Scale Notes plt.xticks (np.linspace (-1, 1, 5)) #x coordinates from -1 to 1 is divided into an average of five points: -1, -0.5, 0.5,1
(. 3) plt.xlabel, plt.ylabel: label axis
(4) plt.title: video title
plt.title (s, * args, ** kwargs)
to add the current chart title, the important parameters are as follows:
S : title content
fontdict: heading styles, is a dictionary
loc: position title, optional 'centet', 'left', 'right'

(5) plt.legend (): Show Legend

Axes settings

plt.axis (): The coordinate axis setting

函数
plt.axis(*v, **kwargs)

主要用于设置坐标轴的属性,返回值为当前的坐标轴范围 [xmin, xmax, ymin, ymax],几种调用方式如下:

调用方式 说明
axis() 返回当前的坐标轴范围 [xmin, xmax, ymin, ymax]
axis(v) 其中 v 为 [xmin, xmax, ymin, ymax]用来设置坐标轴范围
axis(‘off’) 不显示坐标轴和坐标轴名称
axis(‘equal’) x、y轴对应长度所表示的数值相同,提高某一个轴的范围以保持图表大小及比例不变
axis(‘scaled’) x、y 轴对应长度所表达的数值相同,并保持两个轴的数值范围不变,因此需要对图表比例进行调整(缩放)
axis(‘tight’) 在显示所有数据的前提下,尽量减少两个轴的数值范围,并尽量让数据居中
axis(‘image’) 将图表比例按照图片的比例进行调整(缩放)
axis(‘square’) 将图表变成正方形,并确保 (xmax-xmin) 与 (ymax-ymin) 相同
axis(‘auto’) 恢复自动范围
plt.xlim() 和 plt.ylim():x和y轴数值范围

设置并返回 x 轴和 y 轴的数值范围,以 xlim() 为例说明调用方式:

调用方式 说明
xlim() 返回 xmin, xmax
xlim(xmin, xmax) 或 xlim((xmin, xmax)) 设置 x 轴的最大、最小值
xlim(xmax = n) 和 xlim(xmin = n) 设置 x 轴的最大或最小值
plt.xlabel()和plt.ylabel:x轴及y轴的标签

函数
plt.xlabel(label, fontdict=None, labelpad=None, **kwargs)

plt.xticks()和plt.yticks():x轴及y轴刻度

plt.xticks(locs, [labels], **kwargs) # Set locations and labels
locs表示位置,labels决定这些位置上的标签,labels的默认值为和locs相同。

# --coding:utf-8--
import matplotlib.pyplot as plt

# 数据设置
x1 = [0, 5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000];
y1 = [0, 223, 488, 673, 870, 1027, 1193, 1407, 1609, 1791, 2113, 2388];

x2 = [0, 5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000];
y2 = [0, 214, 445, 627, 800, 956, 1090, 1281, 1489, 1625, 1896, 2151];

# 设置输出的图片大小
figsize = 7,5
figure, ax = plt.subplots(figsize=figsize)

# 在同一幅图片上画两条折线
A, = plt.plot(x1, y1, '-r', label='A', linewidth=5.0)
B, = plt.plot(x2, y2, 'b-.', label='B', linewidth=5.0)
# 设置图例并且设置图例的字体及大小
font1 = {'family': 'Times New Roman',
         'weight': 'normal',
         'size': 23,
         }
legend = plt.legend(handles=[A, B], prop=font1)

# 设置坐标刻度值的大小以及刻度值的字体
plt.tick_params(labelsize=23)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]

# 设置横纵坐标的名称以及对应字体格式
font2 = {'family': 'Times New Roman',
         'weight': 'normal',
         'size': 30,
         }
plt.xlabel('round', font2)
plt.ylabel('value', font2)

# 将文件保存至文件中并且画出图
plt.savefig('figure.eps')
plt.show()

plt.figure()的使用

函数

plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)

重要参数

  • num:图像编号或名称,数字为编号 ,字符串为名称
  • figsize:指定figure的宽和高,单位为英寸;
  • dpi:指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80 1英寸等于2.5cm,A4纸是 21*30cm的纸张
  • facecolor:背景颜色
  • edgecolor:边框颜色
  • frameon:是否显示边框

例子1

import matplotlib.pyplot as plt
创建自定义图像
fig=plt.figure(figsize=(4,3),facecolor='blue')
plt.show()
subplot创建单个子图

matplotlib下, 一个 Figure 对象可以包含多个子图(Axes), 可以使用 subplot() 快速绘制, 其调用形式如下 :
subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)

  • 图表的整个绘图区域被分成 numRows 行和 numCols 列
  • 然后按照从左到右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1
  • plotNum 参数指定创建的Axes对象所在的区域

例如,如果 numRows = 2, numCols = 2, 那整个绘制图表样式为 2X2 的图片区域, 用坐标表示为
(1, 1), (1, 2)
(2, 1), (2, 2)
这时, 当 plotNum = 2时,表示的坐标为(1, 2), 即第一行第二列的子图

(1)如果 numRows, numCols 和 plotNum 这三个数都小于 10 的话, 可以把它们缩写为一个整数, 例如 subplot(222) 和 subplot(2,2,2) 是相同的。
(2)subplot在 plotNum 指定的区域中创建一个轴对象. 如果新创建的轴和之前创建的轴重叠的话,之前的轴将被删除。

示例1
规则划分成2*2的

import matplotlib.pyplot as plt

plt.figure()

# 绘制第一个图
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
# 绘制第二个图
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 1])
# 绘制第三个图
plt.subplot(2, 2, 3)
plt.plot([0, 1], [0, 1])
# 绘制第四个图
plt.subplot(2, 2, 4)
plt.plot([0, 1], [0, 1])
a,b,c,d=plt.axis()
print("a:",a," b:",b," c:"," d:",d) #a: -0.05  b: 1.05  c:  d: 1.05
plt.show()

不规则的

import matplotlib.pyplot as plt

plt.figure()

# 绘制第一个图
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# 绘制第二个图
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 1])
# 绘制第三个图
plt.subplot(2, 3, 5)
plt.plot([0, 1], [0, 1])
# 绘制第四个图
plt.subplot(2, 3, 6)
plt.plot([0, 1], [0, 1])
plt.show()
import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2 * np.pi * t)

t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)

plt.figure(12)#12代表第几个figure(左上角)
# 分成2x2,占用第一个,即第一行第一列的子图
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

# 分成2x2,占用第二个,即第一行第二列的子图
plt.subplot(222)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')

# 将整个Figure,分成2x1,占用第二个,即第二行
plt.subplot(212)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

plt.show()
subplots创建多个子图

subplots参数与subplots相似。两者都可以规划figure划分为n个子图,但每条subplot命令只会创建一个子图,而一条subplots就可以将所有子图创建好。subplots返回一个 Figure实例fig 和一个 AxesSubplot实例ax 。
fig, ax = plt.subplots()

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 100)
# 划分子图
fig, axes = plt.subplots(2, 2) #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, -2*x*x+2*x)
plt.savefig("test.jpg")
plt.show()
add_subplot与add_axes新增子图或区域
import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2 * np.pi * t)

t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)
#使用add方式
fig=plt.figure(12)#12代表第几个figure(左上角)
# 分成2x2,占用第一个,即第一行第一列的子图
ax1=fig.add_subplot(221)
ax1.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

# 分成2x2,占用第二个,即第一行第二列的子图
ax2=fig.add_subplot(222)
ax2.plot(t2, np.cos(2 * np.pi * t2), 'r--')

# 将整个Figure,分成2x1,占用第二个,即第二行
ax3=fig.add_subplot(212)
ax3.plot([1, 2, 3, 4], [1, 4, 9, 16])

plt.show()

plt.legend:画图例

1.使用pyplot的方式
legend语法参数如下: matplotlib.pyplot.legend(*args,**kwargs)
一些重要参数如下:
(1)设置图例位置
使用loc参数
plt.legend(loc=‘lower left’)
有下面一些组合:
‘best’ : 0, (only implemented for axes legends)(自适应方式) ‘upper right’ : 1, ‘upper left’ : 2, ‘lower left’ : 3, ‘lower right’ : 4, ‘right’ : 5, ‘center left’ : 6, ‘center right’ : 7, ‘lower center’ : 8, ‘upper center’ : 9, ‘center’ : 10

(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=‘blue’) #设置图例边框颜色
plt.legend(loc=‘best’,facecolor=‘blue’) #设置图例背景颜色,若无边框,参数无效

(4)设置图例标题
plt.legend(loc=‘best’,title=‘figure 1 legend’)

2.使用面向对象的方式
(1)获取并设置legend图例

plt.legend(loc=0, numpoints=1)  
leg = plt.gca().get_legend() #或leg=ax.get_legend()  
ltext = leg.get_texts()  
plt.setp(ltext, fontsize=12,fontweight='bold') 

(2)设置图例

legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')  
legend.get_frame().set_facecolor('red')   #设置图例legend背景为红色  
frame = legend.get_frame()  
frame.set_alpha(1)  
frame.set_facecolor('none') #设置图例legend背景透明  

(3)移除图例
ax1.legend_.remove() ##移除子图ax1中的图例

示例1:显示多图例legend

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(-1, 1, 4)
y = np.random.uniform(-1, 1, 4)
p1, = plt.plot([1, 2, 3])
p2, = plt.plot([3, 2, 1])
l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')

p3 = plt.scatter(x[0:2], y[0:2], marker='D', color='r')
p4 = plt.scatter(x[2:], y[2:], marker='D', color='g')
# This removes l1 from the axes.
plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
# Add l1 as a separate artist to the axes
plt.gca().add_artist(l1)
plt.show()

示例2:

import matplotlib.pyplot as plt
#蓝线
line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
#橘黄色的线
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
# 为第一个线条创建图例
first_legend = plt.legend(handles=[line1], loc=1)
# plt.gca(): 返回当前axes(matplotlib.axes.Axes)
# plt.gcf(): 返回当前figure(matplotlib.figure.Figure)
# plt.clf(): 清理当前figure
# plt.cla(): 清理当前axes
# plt.close(): 一副figure知道显示的调用close()时才会释放她所占用的资源;
# 手动将图例添加到当前轴域
ax = plt.gca().add_artist(first_legend)
# 为第二个线条创建另一个图例
plt.legend(handles=[line2], loc=4)
plt.show()

plt.plot:曲线图、折线图

plt.plot画图时可以设定线条参数。包括:颜色、线型、标记风格。

只提供一个列表或数组(Y向量)-缺省x
如果只提供给plot()函数一个列表或数组,matplotlib会认为这是一串Y值(Y向量),并且自动生成X值(X向量),x的默认值是:range(len(y))

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

提供X,Y向量
也可以给plt.plot()函数传递多个序列(元组或列表),每两个序列是一个X,Y向量对,在图中构成一条折线。

如果要显示的制定X轴的坐标,可以像如下一样:
plt.plot([1,2,3,4],[1,4,9,16])
形成点(1,1),(2,4),(3,9),(4,16)

控制线形(marker)和颜色

(1)线形,默认是实线solid-
    ``'-'``             solid line style
    ``'--'``            dashed line style
    ``'-.'``            dash-dot line style
    ``':'``             dotted line style
    
(2)点的形状:marker,默认为point .
    ``'.'``             point marker
    ``','``             pixel marker
    ``'o'``             circle marker
    ``'v'``             triangle_down marker
    ``'^'``             triangle_up marker
    ``'<'``             triangle_left marker
    ``'>'``             triangle_right marker
    ``'1'``             tri_down marker
    ``'2'``             tri_up marker
    ``'3'``             tri_left marker
    ``'4'``             tri_right marker
    ``'s'``             square marker
    ``'p'``             pentagon marker
    ``'*'``             star marker
    ``'h'``             hexagon1 marker
    ``'H'``             hexagon2 marker
    ``'+'``             plus marker
    ``'x'``             x marker
    ``'D'``             diamond marker
    ``'d'``             thin_diamond marker
    ``'|'``             vline marker
    ``'_'``             hline marker
    
(3)颜色对应如下,默认为蓝色b
    'b'         blue
    'g'         green
    'r'         red
    'c'         cyan
    'm'         magenta
    'y'         yellow
    'k'         black
    'w'         white

示例:
为了区分同一个图里的多条曲线,可以为每个X,Y向量对指定一个参数来标明该曲线的表现形式,默认的参数是’b-’,亦即蓝色的直线,如果想用红色的圆点来表示这条曲线,可以:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16],'ro')

matplotlib不仅仅可以使用序列(列表和元组)作为参数,还可以使用numpy数组。实际上,所有的序列都被内在的转化为numpy数组。同时plot函数还可以同时绘制多条线。

import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0.,5.,0.2)
plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')#绘制三条线,t**2表示t的平方,即每个元素的都平方
plt.show()

线条、marker、颜色可以无顺序任意组合

import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0.,5.,0.2)
plt.plot(t,t,'r--*',t,t**2,'s--b',t,t**3,':g')#绘制三条线,t**2表示t的平方,即每个元素的都平方
plt.axis([0,6,0,20])
#axis()函数接受形如[xmin,xmax,ymin,ymax]的参数,指定了X,Y轴坐标的范围。
plt.show()

plt.scatter:散点图

语法:plt.scatter(x, y, s, c ,marker, alpha,…)

  • x,y: x轴与y轴的数据,都是向量,而且必须长度相等
  • s: 点的面积。想让所有点大小一样就填一个数字,想不一样就填一个向量
  • c: 点的颜色。可填成RGB 三元数或颜色名称或由 RGB 三元数组成的三列矩阵或颜色向量
选项 说明 对应的 RGB 三元数
‘red’ 或 ‘r’ 红色 [1 0 0]
‘green’ 或 ‘g’ 绿色 [0 1 0]
‘blue’ 或 ‘b’ 蓝色 [0 0 1]
‘yellow’ 或 ‘y’ 黄色 [1 1 0]
‘magenta’ 或 ‘m’ 品红色 [1 0 1]
‘cyan’ 或 ‘c’ 青蓝色 [0 1 1]
‘white’ 或 ‘w’ 白色 [1 1 1]
‘black’ 或 ‘k’ 黑色 [0 0 0]
#不同颜色的点
cValue = ['r','y','g','b','r','y','g','b','r']
plt.scatter(x,y,c=cValue)
  • marker: 点的形状
  • alpha: 透明度。[0,1]:1不透明,0透明
  • edgecolors:轮廓颜色。和c类似,参数也相同
  • linewidths:线宽。标记边缘的宽度,默认是’face’

注意事项
color、marker等不能同时作为一个参数,plt.scatter(x1, y1, ‘bo’, s=5)不合法。

示例1:

from numpy import *  
import matplotlib  
import matplotlib.pyplot as plt  
import numpy as np
x = random.rand(50,30)      #创建一个50行30列的多维数组(ndarray)
#basic  
f1 = plt.figure(1)          #创建显示图形输出的窗口对象
plt.subplot(211)            #创建子坐标系
#x[:,1]获取第二列作为一维数组,x[:,0]获取第一列作为一维数组
plt.scatter(x[:,1],x[:,0])  #画散点图


# with label  
plt.subplot(212)            #c重新创建坐标系

#list(ones(20))     创建1行20列的全为1列表
#list(2*ones(15))   创建1行15列全为2的列表
#list(3*ones(15)    创建1行15列全为3的列表

label = list(ones(20))+list(2*ones(15))+list(3*ones(15))    #将列表合并到一起,共50列
label = array(label)                                        #将列表转为数组

#15.0*label         将数组的每个值都乘以15.0
#x[:,1]             将x的第2列50行转为1行50列
#x[:,0]             将x的第1列50行转为1行50列

#x轴和y轴均50个点,两个Label都是1行50列的数组
#从第一个点到第20个点的样式相同,从第21到第35个点相同,从第36到第50个点相同
plt.scatter(x[:,1],x[:,0],15.0*label,15.0*label)  

# with legend  
f2 = plt.figure(2)              #创建显示图形输出的窗口对象
idx_1 = np.where(label==1)      #找label中为1的位置

#画图  marker标识散点图样式 color标识颜色  label表示图例的解释   s表示散点的大小
p1 = plt.scatter(x[idx_1,1], x[idx_1,0], marker = 'x', color = 'm', label='1', s = 30)  
idx_2 = np.where(label==2)      #找label中为2的位置

p2 = plt.scatter(x[idx_2,1], x[idx_2,0], marker = '+', color = 'c', label='2', s = 50)  
idx_3 = np.where(label==3)      #找label中为3的位置    

p3 = plt.scatter(x[idx_3,1], x[idx_3,0], marker = 'o', color = 'r', label='3', s = 15)  
plt.legend(loc = 'upper right')  #图例的位置

plt.show()

Python matplotlib(2D绘图库)2

Guess you like

Origin blog.csdn.net/yyl424525/article/details/92721499