Detailed Python module module --matplotlib

Pyplot introductory tutorials and examples herein reference document Pyplot tutorial


Analysis examples

1. Basic drawing polyline

Drawing (0,0), (1,1), (2,1), (3,3) connected to the four points of the polyline

import matplotlib.pyplot as plt
x=[0,1,2,3]
y=[0,1,1,3]
plt.plot(x,y)
plt.show()

 

Here Insert Picture Description


2. Modify the shape of a line chart color / line

plt.plot(x,y,'r')   # 修改颜色,rgb=红绿蓝,默认为蓝
plt.plot(x,y,'--')  # 修改线的形状为虚线,默认为折线'-',另外'o'为点,'^'为三角
plt.plot(x,y,'g--') # 一起修改为绿色虚线
plt.axis([1,6,0,5]) # 修改坐标轴x刻度显示

 

Here Insert Picture Description

3. Enter the case where only one-dimensional data

plt.plot (x, y) to accept the set of points (X, y), only when the input of one-dimensional data processing as the y-axis, x-axis generated by default [0,1,2, ...]
for example, drawing four independent the point (0,1), (1,1), (2,1), (3,1)

y=[1,1,1,1]
plt.plot(y,'ro')
plt.show()

 

Here Insert Picture Description

4.list与Arrays

Original tutorial


If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally.

For performance issues, means that all sequences (including list, etc.) are converted to numpy.array inside

t1=[1,5,1,5] #list会被转换为t2的类型
t2=np.array([5,1,5,1]) #numpy.array
plt.plot(t1)
plt.plot(t2) 
plt.show()


The display a plurality of graphs in FIG.

In the fourth, we are used twice plt.plot () Loading t1 and T2, may be a single statement

plt.plot(t1,'b--',t2,'r--')

For both groups (x, y) coordinates, as follows

x1=[1,2,3,4]
y1=[1,2,3,4]
x2=[2,4,6,8]
y2=[4,8,12,16]
plt.plot(x1,y1,'r-',x2,y2,'g--')
plt.show()

Here Insert Picture Description

 

6. Draw the standard curve function: sin () and cos ()

Draw f (x) = sin (x) and g (x) = cos (x) image x∈ [0,20] in

x = np.arange(0, 20, 0.01)
plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b--')
plt.axis([0,20,-3,3])
plt.show()

 

Here Insert Picture Description

The display grid lines

x = np.arange(0, 20, 0.01)
plt.plot(x, x**2)
plt.grid(True)  # 设置网格线
plt.show()

 

Here Insert Picture Description


8. marked increase


7 as a function of the image as an example. Note that the block distortion appears Chinese input
(1) increase in x, y-axis text

plt.xlabel("Money Earned")
plt.ylabel("Consume Level")


(2) increase in headline

plt.title("Figure.1")


(3). FIG text within
the specified x-axis appears the first word, y-axis, the text itself

plt.text(2.5,100,"TEXT1")


(4) an arrow indicating
the specified text, the arrow points to the coordinates, the coordinates of the text display, the properties of the arrow

plt.annotate('max value', xy=(20, 400), xytext=(12.5, 400),
             arrowprops=dict(facecolor='black', shrink=0.05),
             )


(5) Integrated Results Figure

Here Insert Picture Description


9. Set the Text property


Of text (), xlabel (), ylabel (), title (), annotate () like text attributes parameter settings may be used
e.g.

plt.xlabel("Money Earned",color="r",fontsize=20)

Here Insert Picture Description

Optional parameters are as follows, listed here only common properties, more properties please refer to
https://matplotlib.org/api/text_api.html#matplotlib.text.Text


10. Set Curve Properties


plt.plot () Returns matplotlib.lines.Line2D , variable and can be obtained by modifying curves Line2D properties

x=np.arange(0,10,0.01)
line1,line2=plt.plot(x,np.sin(x),'-',x,np.cos(x),'--') #line1得到2D Lines 
plt.setp(line1,color='r',linewidth='11.0') #设置曲线的宽度
plt.show()

 

Here Insert Picture Description


11. solve the Chinese garbled


9 using the modified font Chinese font can easily solve the garbage
(1) designated as the font files in a directory

from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc") 
plt.xlabel("中文文本", fontproperties=font) 


(2) designated as the system font

plt.xlabel("中文文本",fontname='SimHei',size=20)
#或者
plt.xlabel("中文文本",fontproperties='SimHei',fontsize=20)#size要放在后面,否则会被覆盖


(3) Global Settings

font = {'family' : 'SimHei',
        'weight' : '50',
        'size'   : '30'}
plt.rc('font', **font)
plt.xlabel("中文文本")



12. The modified axis scale


(1) specified scale range

plt.axis([0,6,1,5]) #设定x轴刻度在(0,6) y轴刻度在(1,5)
plt.axis('off')  #关闭刻度


Scale modification (2) of the subgraph

axes[0,0].set_xticks([0,250,750,1000]) #设置x轴
axes[0,0].set_xticklabels(['one','two','three'],rotation=30) #将数值改为标签,并旋转30度显示


(3) using the scale function
of a tutorial example Example

Here Insert Picture Description

Four different scale

plt.yscale('linear')
plt.yscale('log')
plt.yscale('symlog')
plt.yscale('logit')


The four following example code of FIG.

from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure(1)

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)


# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)


# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()


13. graphing: circular / rectangular / oval

 

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig = plt.figure() 
ax1 = fig.add_subplot(111,aspect='equal') #1x1一张图中的第1张,equal为等宽显示
rec=patches.Rectangle((0, 0), 8, 4) #顶点坐标(0,0)  宽w=8 高h=4
cir=patches.Circle((8,8),2)  #圆心坐标(8,8) 半径r=1
ell=patches.Ellipse((2,8),6,3) #椭圆左顶点坐标(2,8) 长轴c1=6 短轴c2=3
ax1.add_patch(rec) #插入patch图像
ax1.add_patch(cir)
ax1.add_patch(ell)
plt.plot() #显示多个
plt.show() 

Here Insert Picture Description

patches There are many kinds of graphics such as various arrows, arrows, and other polygons.

14. histogrammed - standard normal distribution


plt.hist () is used to draw a histogram


[Mu], also known as standard normal distribution, the mean is μ = 0, the normal distribution standard deviation σ = 1, denoted by N (0,1)
code is as follows

mu, sigma = 0,1
x = np.random.normal(mu,sigma,10000)
n, bins, patches = plt.hist(x,bins=100,facecolor='g', alpha=0.75)
plt.text(-3, 250, r'$\mu=0,\ \sigma=1$')
plt.grid(True)
plt.show()

 

Here Insert Picture Description


15. Draw a scatter plot

plt.scatter () is used to draw scattergram


Example: positions 1000 to draw normal random distribution points

x = np.random.normal(0, 1, 1000)  # 1000个点的x坐标
y = np.random.normal(0, 1, 1000) # 1000个点的y坐标
c = np.random.rand(1000) #1000个颜色
s = np.random.rand(100)*100 #100种大小
plt.scatter(x, y, c=c, s=s,alpha=0.5)
plt.grid(True)
plt.show()

 Here Insert Picture Description


16. A plurality of graph display

names = ['Anime', 'Comic', 'Game']
values = [30, 10, 20]
plt.subplot(221)  #构建2x2张图中的第1张子图
plt.bar(names, values) #统计图
plt.subplot(222)
plt.scatter(names, values) #散点图
plt.subplot(223)
plt.plot(names, values) #折线图
plt.suptitle('三种图示',fontname='SimHei')
plt.show()

Here Insert Picture Description

The above is a configuration of each sub-picture, and then draw in the submap It is also possible to construct all of the sub-picture, and then specify the drawing sheets in which sub-picture by the subscript

fig,axes=plt.subplots(2,2) #构造2x2的子图
axes[0,1].plot(names, values) #通过下标访问
axes[1,0].scatter(names, values)
axes[1,1].bar(names, values)
plt.show()

 

Here Insert Picture Description


17. FIG sub-interval adjustment

 

fig,axes=plt.subplots(2,2,sharex=True,sharey=True) #构造2x2的子图,子图共享x,y轴
for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.rand(500),bins=100,alpha=0.7,color='k')
plt.subplots_adjust(hspace=0,wspace=0) #修改内部的宽,高间距为0
plt.show()


(And can not be obtained in the same book python3.7 result, i.e. there is no data to achieve an internal spacer sub-picture visualization)

Here Insert Picture Description


18. Draw a bar graph


Vertical histogram plt.bar (name, values)
level histogram plt.barh (name, values)

x=np.random.randint(1,10,8)
label=list('abcdefgh')
plt.subplot(211)
plt.bar(label,x)
plt.subplot(212)
plt.barh(label,x)
plt.show()

Here Insert Picture Description

 

A vertical bar graph comparing the two sets of data
no longer uses plt.bar () , but the use of pd.DataFrame.plot.bar ()

x=np.random.randint(1,10,8)
y=np.random.randint(1,10,8)
data=pd.DataFrame([x,y],index=['X','Y'],columns=list('abcdefgh'))
>>> data
data
   a  b  c  d  e  f  g  h
X  6  2  9  5  5  2  7  7
Y  6  6  9  1  1  5  2  4
data.plot.bar()
plt.show()

Here Insert Picture Description

To obtain a classification index, histogram data columns
two data cross bar graph comparing vertical, and simply exchange columns to index

data.transpose().plot.bar() #data.transpose()转置
plt.show()

Here Insert Picture Description

 

Published 352 original articles · won praise 115 · views 130 000 +

Guess you like

Origin blog.csdn.net/Aidam_Bo/article/details/103326999