Basic usage of matplotlib in Python

Basic usage of matplotlib in Python

01. Introduction

Basically every computer language can draw images. In scientific computing, the drawing ability of matlab and R is very powerful. But for programmers who love python, python drawing graphics is also good. Of course, here you need to know some basic knowledge, numpy for data processing , and a numpy matplotlib package. When these environments are ready, you can try to write some basic graphics.
What needs to be added here is to install numpy and matplotlib in the window system, dos window: pip install numpy; pip install matplotlib;

02. Basic introduction to drawing

Here is the code to show, you can check the code for details:

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,50) #-3  --3 50个点
y1=x*2+1
y2=x**2
#第一张figure,一下都是其内容
plt.figure("第一个图") #为该figure设置参数
plt.plot(x,y1)

#第二张figure
plt.figure("第二个图")
l1,=plt.plot(x,y2,label='up')  #为曲线设置标签
l2,=plt.plot(x,y1,color='red',linewidth=5.0,linestyle='--',label='down')
#图例设置,曲线设置label
#r如果想打印一条如:l1,可以handles=[l1],label=['aaa',]
plt.legend(handles=[l1,l2,],labels=['aaa','bbb'],loc='best')
#给坐标轴设置范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#设置坐标参数
plt.xlabel("I am x")
plt.ylabel("I am y")
#设置角标
new_ticks=np.linspace(-1,2,5) #5个点
print(new_ticks)
plt.xticks(new_ticks)
#y轴对应值设置,使用$设置字体, a $\alpha
plt.yticks([-2,-1.8,-1,1.22,3], [r'$really\ bad$',r'$bad \ \alpha$',r'$normal$',r'$good$',r'$really\ good$'])
#设置坐标轴的位置
ax=plt.gca() #获取坐标轴对象
#设置上右轴为none
ax.spines['right'].set_color('none')   #四个边框
ax.spines['top'].set_color('none') 
#将原图的左、下边框设置坐标轴对象的左、下边框
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#挪动边框,设置坐标原点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
#把所有的数据显示
plt.show()

03. The result of running the above program

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326134799&siteId=291194637