Python-matplotlib drawing (study notes)

What is Matplotlib?

Matplotlib is a python 2D plotting library , which generates publication-quality graphics in various hardcopy formats and a cross-platform interactive environment. With Matplotlib, developers can generate plots, histograms, power spectra, bar graphs, error graphs, scatter plots, etc. with just a few lines of code.

Simple to use
import  matplotlib.pyplot as plt
squares=[1,2,3,4,5]
plt.plot(squares)

plt.show()

Operating results:
Insert picture description here
Note:
1. If you don't use plo.show(), the chart will not be displayed, because you may have to describe the chart in various ways, so unnecessary errors can be avoided by calling show() explicitly.

Figure object

I will take out the objects one by one here, and then summarize them later. In matplotlib, the entire chart is a figure object. In fact, each pop-up window is a Figure object, so how to create multiple Figure objects in one code, that is, multiple small windows?
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class'matplotlib.figure.Figure'>, clear=False, **kwargs )
(1) num: This parameter is an optional parameter, that is, it can be given or not given. The num can be understood as the attribute id of the window, that is, the identity of the window.
If this parameter is not provided, the parameter will be incremented when the window is created. If provided, the window will exist with the num as the Id.
(2) figsize: optional parameter. Integer tuple, default is none.
If an integer tuple is provided, the tuple will be the length and width. If not provided, the default is rc fiuguer.figsize.
For example (4, 4) means that a window is created with a length of 4 inches and a width of 4 inches.
(3) dpi: optional Parameters, integers. Indicates the resolution of the window, if not provided, the default is figure.dpi
(4) facecolor: optional parameter, representing the background color of the window, if not provided, the default is figure.facecolor
The color setting is through RGB, and the range is '#000000'~'#FFFFFF', where 16 bits per 2 bytes represent 0-255 of RGB.
For example,'#FF0000' means R:255 G:0 B:0 means red.
(5) edgecolor: optional parameter, indicating the border color of the window, if not provided, the default is figure, edgecolor
(6) frameon: optional parameter, indicating whether to draw the frame of the window, the default is
(7) figureclass: not yet Understand
(8) clear: optional parameter, the default is false, if the provided parameter is true, and the window exists, the window content will be cleared.

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-1,1,100)
y1=x**2
y2=x*2
#这是第一个figure对象,下面的数据都会在第一个figure中显示
plt.figure()
plt.plot(x,y1)
#这里是第二个figure对象,下面的数据都会在第二个figure中显示
plt.figure(num=3,figsize=(10,5))
plt.plot(x,y2,color='red',linewidth='3.0',linestyle='--')
plt.show()

Insert picture description here
The things to note here are:

  • We look at the window of each image above, we can see that the figure does not start from 1 and then go to 2. This is because when we created the second figure object, we specified a parameter of num = 3, so the second Figure3 displayed on the window title.
  • For each window, we can also specify the size of the window separately for them. That is, the figsize parameter.
  • If we want their lines to be different, we can use the following statement to modify
plt.plot(x,y2,color = 'red',linewidth = 3.0,linestyle = '--')
Detailed use of numpy.linspace

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
returns evenly spaced numbers within the specified interval.
Return num uniformly distributed samples in [start, stop].
The endpoints of this interval can be excluded arbitrarily.
Learn more .

Set axis

  • Change the range of x and y values ​​displayed on the chart
  • Set a name for the horizontal and vertical coordinates
  • Change the coordinate axis to a different unit
import matplotlib.pyplot as plt
import numpy as np
import math

x = np.linspace(-1,2,5)#生成-1到2并且个数为5的一组点(以队列的形式)
plt.xticks(x)#以生成的横坐标作为描点
y=2*x
#在对应坐标处更换名称
plt.yticks([-2,-1,0,1,2],['really bad','b','c','d','good'])
plt.xlim(-1,2)#截取0-1的x轴
plt.ylim(-2)#从y=0开始截取y轴
plt.xlabel("x")#设置x轴名称
plt.ylabel("y")
plt.plot(x,y,color="#faf",linewidth=4,linestyle='-')#设置函数线条的颜色,粗细和风格
plt.show()

Run screenshot
Insert picture description here

legend

We often add multiple lines to one figure, so how do we distinguish between multiple lines? Legend is used here.
plt.legend(handles = [l1,l2],labels = ['up','down'],loc ='best',shodow=True)
Once the labels attribute is used in the legend() function, then in the plot The label set in the function will be invalid. If the parameters set in the labels are less than the parameters of the handsels, then how many parameters in the labels will show how many function information in the legend.
For the return value of the plot function, if you want to use the handle attribute of the legend function, you must add a',' to the return value of the plot function.
loc represents the display position of the legend. The default display position is'best', which means it is displayed in the picture in the best way, with as few occlusion functions as possible.

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(0,4,50)
y1=2*x
y2=4*x

# 简单的使用
l1, = plt.plot(x, y1, label='linear line')#注意','很重要
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')

# 简单的设置legend(设置位置)
#方式一
plt.legend(loc='center')#(lower,center,upper)和(left,center,right)之间进行组合,还有特殊的‘center'指位于图中间,'best'表示放在遮住数据最少的位置
#方式二
plt.legend(loc="best",handles =[l1,l2],labels=["line1","line2"],shadow=True)
plt.show()

Run screenshot
Insert picture description here

Add some annotations on the picture

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2 * x + 1

plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
print("----重新设置x轴和y轴-------")
# 将底下的作为x轴
ax.xaxis.set_ticks_position('bottom')
# 并且data,以x轴的数据为基本
ax.spines['bottom'].set_position(('data', 0))

# 将左边的作为y轴
ax.yaxis.set_ticks_position('left')
# 并且data,以y轴的数据为基本
ax.spines['left'].set_position(('data', 0))

print("------- 注解方式一 -----------")
x0 = 1
y0 = 2 * x0 + 1

plt.plot([x0, x0], [0, y0], "k--", linewidth=2.5, color='red')
plt.plot([0, x0], [y0, y0], 'k--', linewidth=2.5, color='red')
plt.scatter([x0], [y0], s=50, color='b')
plt.annotate(r'$2x+1 = %s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points',
             fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))

plt.show()

note:

  • xy is the horizontal and vertical coordinates of the point to be annotated;
  • xycoords ='data' indicates that the xy coordinates of the point to be annotated are based on the horizontal and vertical axis;
  • xytext=(+30,-30) and textcoords='data' indicate that the text here is based on the offset of the x coordinate of the marked point +30 and the y coordinate of the marked point -30, which is where we want to annotate the text ;
  • fontsize = 16 means the size of the font;
  • arrowprops = dict() This is the description of this arrow, arrowstyle='->' this is the type of arrow, connectionstyle="arc3,rad=.2" these two describe the arc and angle of our arrow.
    The first way to add tags
    Insert picture description here
plt.annotate(r'$2x+1 = %s$'% y0,xy = (x0,y0),xycoords = 'data',
             xytext=(+30,-30),textcoords = 'offset points',fontsize = 16
             ,arrowprops = dict(arrowstyle='->',
                                connectionstyle="arc3,rad=.2"))

The second way to add tags
Insert picture description here

print("-----方式二-----")
plt.text(-3.7,3,r'$this\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={
    
    'size':16,'color':'r'})

Types of drawing

scatter chart
import matplotlib.pyplot as plt
import numpy as np

# 数据个数
n = 24

# 用np.random.normal生成随机数,返回 列表。其中参数为 平均数是0,方差是1,生成n个数
X = np.random.normal(0, 1, n)
# 用np.random.normal生成随机数,返回 列表。其中参数为 平均数是0,方差是1,生成n个数
Y = np.random.normal(0, 1, n)


# T代表点的颜色
T = np.arctan2(Y, X)  # for color value
np.arctan2(X, Y)

plt.scatter(X,Y,s=75,c=T,alpha=0.5)

# plt.scatter(np.arange(5), np.arange(5))
# plt.xlim(-1.5,1.5)
# plt.ylim(-1.5,1.5)

# 将x轴y轴的下标设为空
plt.xticks([])
plt.yticks(())

plt.show()

Insert picture description here

Histogram
import matplotlib.pyplot as plt
import numpy as np

n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)

plt.bar(X, Y1, 0.6, None, facecolor="#9999ff", edgecolor='white')
plt.bar(X, -Y2, 0.6, None, facecolor='#ff9999', edgecolor='white')
# ha:horizontal alignment  水平对齐
# va:Vertical alignment 垂直对齐
for x, y in zip(X, Y1):
    plt.text(x, y + 0.01, '%.2f' % y, ha='center', va='bottom', fontdict={'size': 10, 'color': "red"})
for x, y in zip(X, Y2):
    plt.text(x, -y - 0.01, '%.2f' % y, ha='center', va='top')

plt.show()

Insert picture description here

Contours contour map
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
    # 计算高度的函数
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)

# 把x,y绑定成网格的输入值
X, Y = np.meshgrid(x, y)
# 把颜色放入等高线内
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)

# 画等高线的线
C = plt.contour(X, Y, f(X, Y), 8, alpha=1, colors='green', linewidths=0.5)

# 给等高线加上label描述
plt.clabel(C, inline=True, fontsize=10, colors='black')
plt.show()

Insert picture description here

image
import matplotlib.pyplot as plt
import numpy as np
import random

list1 = []
for i in range(9):
    list1.append(random.random())

print(list1)
print(type(list1))

list1 = np.random.normal(0, 1, 9)
print(type(list1))
# a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
#               0.365348418405, 0.439599930621, 0.525083754405,
#               0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3)
a = np.array(list1).reshape(3, 3)
print(a)
print(type(a))
plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper')
# 显示colorbar,shrink表示压缩为图片的长的多少
plt.colorbar(shrink=0.7)
plt.xticks(())
plt.yticks(())
plt.show()

Insert picture description here
Learn more about cmap .

3D data
import matplotlib.pyplot as plt
import numpy as np
# 画3D图必须引入的包
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = Axes3D(fig)
# 取得X,Y的值
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)

Z = np.cos(R)
# 画出3D图,rstride表示横坐标跨度,cstride表示纵坐标跨度
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))

ax.contourf(X, Y, Z, zdir='z', offset=2, cmap='rainbow')

ax.set_zlim3d(-2, 2)
plt.show()

Insert picture description here

Multi-picture combined display

Use the subplot function

All-in-one display

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# ax=plt.gca()
# #右边的脊梁
# ax.spines['right'].set_color('none')
# ax.spines['top'].set_color('none')
# print("----重新设置x轴和y轴-------")
# # 将底下的作为x轴
# ax.xaxis.set_ticks_position('bottom')
# # 以y轴的数据为基本,设置‘bottom’脊梁的位置
# ax.spines['bottom'].set_position(('data', 0.5))#axes定义百分比位置
#
# # 将左边的作为y轴
# ax.yaxis.set_ticks_position('left')
# # 以x轴的数据为基本,设置‘left’脊梁的位置
# ax.spines['left'].set_position(('data', 0.5))


plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 2])

plt.subplot(2, 3, 5)
plt.plot([0, 1], [0, 1])

plt.subplot(2, 3, 6)
plt.plot([0, 4], [0, 4])
plt.show()

Insert picture description here
Subplot separated display

import matplotlib.pyplot as plt
import numpy as np
#第二种分隔显示需要导入的模块
import matplotlib.gridspec as gridspec

#方法一:subplot2.grid
plt.figure()
ax1=plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
ax1.plot([1,2],[1,2])
#ax1.set_title()==plt.title()类似的都用set_
ax1.set_title('ax1_title')
ax2=plt.subplot2grid((3,3),(1,0),colspan=2)
ax3=plt.subplot2grid((3,3),(1,2),rowspan=2)
ax4=plt.subplot2grid((3,3),(2,0))
ax5=plt.subplot2grid((3,3),(2,1))

#方法二:gridspec
plt.figure()
gs=gridspec.GridSpec(3,3)
ax1=plt.subplot(gs[0,:])
ax2=plt.subplot(gs[1,:2])
ax3=plt.subplot(gs[1:,2])
ax4=plt.subplot(gs[-1,0])
ax5=plt.subplot(gs[-1,-2])

#方法三:easy to define structure

f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2],[1,2])
plt.tight_layout()
plt.show()

Insert picture description here
Figure figure

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
left, bottom, width, height = 0.15, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')

left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'g')

plt.axes([.6, .2, .25, .25])
# y[::-1]将y中数据进行逆序
plt.plot(y[::-1], x, 'b')

plt.show()

Insert picture description here
Secondary axis

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = 0.05 * x ** 2

y2 = -1 * y1
fg, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel("X data")
ax1.set_ylabel("Y1", color='g')

ax2.set_ylabel("Y2", color='b')

plt.show()

Insert picture description here
animation

import matplotlib.pyplot as plt
import numpy as np
# 动画需要导入的模块
from matplotlib import animation

fig, ax = plt.subplots()

x = np.arange(0, 2 * np.pi, 0.01)
line, = ax.plot(x, np.sin(x))


def animation1(i):
    global line
    line.set_ydata(np.sin(x + i / 150 * np.pi * 2))
    return line


def init1():
    line.set_ydata(np.sin(x))
    return line,


ani = animation.FuncAnimation(fig=fig, func=animation1, frames=150, init_func=init1, interval=20, blit=False)

plt.show()

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44788518/article/details/108922841