当前位置:网站首页>matplotlib pyplot
matplotlib pyplot
2022-08-01 05:20:00 【Lonely boat fishing cold river snow】
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
print(matplotlib.__version__) # 3.3.4
综述
- color
b(blue)
r(red)
g(green)
y(yellow)
m(magenta)
k(black)
w(white)
c(cyan)
- linestyle
'-'实线
'--'破折线
'-.'点划线
':'虚线
- maker
'.'点
','像素
'o'实心圆圈
'v'倒三角
'^'上三角
'>'右三角
'<'左三角
'1'下三叉
'2'上三叉
'3'左三叉
'4'右三叉
'8'八角形
's'正方形
'p'五边形
'*'星号
'h'六边形
'd'瘦菱形
'+'加好
'X'乘号
plot()
绘制二维图形xlable(),ylable()
设置x轴和y轴标签title()
设置标题
# plot([x], y, [fmt], *, data=None, **kwargs) Article draw single
# plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) Draw more lines
# fmt ='[marker][line][color]' E.g o:r 实心圆 虚线 红色
# 两点(0,0) (6, 100)绘制一条直线
x = np.array([0, 6])
y = np.array([0, 100])
plt.plot(x, y)
plt.show()
# Draw the irregular line,x自动生成
y = np.array([3, 8, 1, 10, 5, 7])
plt.plot(y,'o:r')
plt.show()
# Draw a sine,A cosine
x = np.arange(0, 4*np.pi, 0.1) # start,stop,step
y = np.sin(x)
z = np.cos(x)
plt.plot(x,y,x,z)
plt.show()
# Draw two different lines
x = np.arange(1, 11)
y = 2*x + 5
plt.plot(x, y, '*:r',label='line 1')
y = (x**2)-2
plt.plot(x, y, 'v-.g',label='line 2')
plt.title('Matplotlib Demo')
plt.xlabel("x axis")
plt.ylabel('y axis')
plt.legend() # 设置图例
plt.show()
1. 网格线
# Matlablib 网格线grid()
y = np.array([3, 1, 16, 9])
plt.plot(y, 'gh:')
plt.grid(color='r', linestyle='-.', linewidth=2, axis='x') # Set in the axial direction display grid lines
plt.show()
2. 多图
# Matplotlib 绘制多图 subplot()
x = np.arange(0, 4*np.pi, 0.1)
y_sin = np.sin(x)
plt.subplot(2, 2, 1) # Painting area divided into2行2列,编号1
plt.title("Sine")
plt.plot(x, y_sin)
y_cos = np.cos(x)
plt.subplot(2, 2, 2) # Painting area divided into2行2列,编号2
plt.title('Cosine')
plt.plot(x, y_cos)
y_tan = np.tan(x)
plt.subplot(2,2,3) # Painting area divided into2行2列,编号3
plt.title('Tansine')
plt.plot(x, y_tan)
y_exp = np.exp(x)
plt.subplot(2,2,4) # Painting area divided into2行2列,编号4
plt.title('Exp')
plt.plot(x, y_exp)
plt.suptitle('RUNOOB subplot')
plt.show()
# Matplotlib绘制多图 subplots() 创建一个画像figure和一组子图subplots,返回figThe whole picture,ax代表坐标轴和画的图
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
fig, ax = plt.subplots()
ax.plot(x, y, marker='o',label='line')
ax.set_xlabel('x - axis')
ax.set_ylabel('y - axis')
ax.set_title('Simple plot')
ax.legend()
fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax2.scatter(x, y)
plt.suptitle('sharey=True')
fig, axs = plt.subplots(2,2, subplot_kw=dict(projection='polar'))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
plt.suptitle('polar')
plt.subplots(2,2,sharex='col')
plt.suptitle("sharex='col'")
plt.subplots(2,2,sharex=True,sharey=True)
plt.suptitle("sharex='True', sharey='True'")
fig, ax = plt.subplots(num=10, clear=True)
plt.show()
3. 散点图
# Matplotlib 散点图 scatter()
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([1,4,9,16,7,11,23,18])
sizes = np.array([20,50,100,200,500,1000,60,90]) # 设置图标大小
colors = np.array(['red','green','black','orange','purple','beige','cyan','magenta']) # 自定义点的颜色
plt.scatter(x,y,s=sizes, c=colors)
plt.show()
# 设置两组散点图
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y, color="hotpink")
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color="#88c999")
plt.show()
# Random set scatterplot
np.random.seed(19680801) # 随机数生成器的种子
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30*np.random.rand(N))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c = colors, alpha=0.5) # 设置标记大小、颜色、透明度
plt.title('Rand Scatter')
plt.show()
# 设置颜色条
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.title("Setting colormap")
plt.show()
4. 柱状图
# Matplotlib 柱状图 bar()
np.random.seed(0)
x = np.array([1,3,5,7,9])
x2 = np.array([2,4,6,8,10])
y = np.random.rand(5)
y2 = np.random.rand(5)
plt.bar(x, y, color = "#4CAF50",align="center")
plt.bar(x2, y2, color='g', align='center')
plt.title('Bar graph')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.show()
# Set the direction of the vertical bar chart barh()
x = np.array(["runoob-1", 'runoob-2','runoob-3','C-runoob'])
y = np.array([12,22,6,18])
plt.barh(x,y,color=["#4CAF50","red","hotpink","#556B2F"])
plt.title("barh()")
plt.show()
5. 饼图
# Matplotlib 饼图 pie()
y = np.array([35, 25, 25, 15])
plt.pie(y, labels=['A', 'B', 'C', 'D'],
colors = ['#d5695d','#5d8ca8','#65a479','#a564c9'],
explode=(0,0.2,0,0), # 第二部分突出显示,值越大,距离中心越远
autopct='%.2f%%' #格式化输出百分比
)
plt.title('pie()')
plt.show()
6. 直方图
# Matplotlib 直方图 hist
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
plt.hist(a, bins=[0, 20, 40, 60, 80, 100])
plt.title('Histogram')
plt.show()
7. 绘制函数图像
# 绘制函数图像
# plt.rcParams["font.sans-serif"]=["Heiti TC"] # mac系统
# plt.rcParams["font.sans-serif"]=["SimHei"] # windows系统
# plt.rcParams["axes.unicode_minus"]=False # Can make the negative on the axis coordinate normal appear
x = np.linspace(-5,5,20)
y1=2*x+1
y2=x**2
plt.figure(num=3,figsize=(8,8),dpi=None,facecolor=None,edgecolor=None,frameon=True)
l1,= plt.plot(x,y2,'b:o') # return a list of lines representing the ploted data.
l2,= plt.plot(x,y1,color='red',marker='d',linewidth=1.0,linestyle='--',alpha=0.9)
# 设置图例
plt.legend(handles=[l1,l2],labels=['linear line','square line'],loc='best')
# 设置坐标轴标签
plt.xlabel('x axis')
plt.ylabel('y axis')
# Set the axis of minimum and maximum value
plt.xlim((-3,4))
plt.ylim((-2,3))
# Change the axis labels
new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks, rotation='vertical',fontsize=12)
plt.yticks([-2,-1.8,-1,1.22,3],
[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'],rotation=90,fontsize=12)
# 坐标轴移动,4个spines(支柱),top,bottom,left,right
ax=plt.gca()
ax.spines['right'].set_color('none') # Set the color of the pillar on the right is empty(Or moved to the leftx轴0处)
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') # Lock at the bottom of thex轴
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0)) # 'data'表示按数值挪动,其后数字代表挪动到y轴的刻度值
ax.spines['left'].set_position(('data',0))
# 设置网格线
plt.grid(visible=None, which='major', axis='y', ls=':',lw=2,c='y',alpha=0.8)
# 绘制参考线
plt.axvline(x=0.5, c='black', ls='-', lw=2)
plt.axhline(y=1.0, c='black', ls='-.', lw=2)
# Drawing reference field
plt.axvspan(xmin=-0.5, xmax=1.0, facecolor='gray', alpha=0.4)
plt.axhspan(ymin=-1.0, ymax=0.5, facecolor='rosybrown', alpha=0.4)
#标记坐标点
plt.text(0.5, 0.5, "marked", c='black',alpha=0.7, fontsize=12)
#添加注释文本
plt.annotate("minimum",xy=(1, 0.5), xytext=(1.2, 0.3),color='r',alpha=0.7,
weight="bold",fontsize=12,arrowprops=dict(arrowstyle="->",
connectionstyle="arc3",color="b"))
# 填充
plt.fill_between(x,y1,0,facecolor='gray',alpha=0.4)
# 保存图像
plt.savefig('./123.png')
# 显示图像
plt.show()
边栏推荐
- 2022.7.27好题选讲
- 使用string 容器翻转 字母
- typescript23-tuple
- Check控件
- Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums
- (2022牛客多校四)N-Particle Arts(思维)
- 56:第五章:开发admin管理服务:9:开发【文件上传到,MongoDB的GridFS中,接口】;(把文件上传到GridFS的SOP)
- 移动应用恶意攻击激增500% 三六零天御为APP免费构建安全屏障
- typescript26 - literal types
- (2022牛客多校四)H-Wall Builder II(思维)
猜你喜欢
Selenium: Popup Handling
状态压缩dp
The method of solving stored procedure table name passing through variable in mysql
MySQL-数据定义语言-DDLdatebase define language
PaddleX部署推理模型和GUI界面测试结果不一致的解决方法
力扣(LeetCode)212. 单词搜索 II(2022.07.31)
(2022 Niu Ke Duo School IV) N-Particle Arts (Thinking)
A,H,K,N
MySQL-DML language-database operation language-insert-update-delete-truncate
pytroch、tensorflow对比学习—使用GPU训练模型
随机推荐
PAT serie b write the number 1002
2022/07/29 入职健海JustFE团队,我学到了高效开发(年中总结)
PAT class B 1001 (3n+1) conjecture
The method of solving stored procedure table name passing through variable in mysql
Pyspark Machine Learning: Vectors and Common Operations
Selenium:弹窗处理
Challenge 52 days to memorize Peppa Pig (Day 01)
MySQL-Data Operation-Group Query-Join Query-Subquery-Pagination Query-Joint Query
What should I do if the neural network cannot be trained?
Risk strategy important steps of tuning method
II. Binary tree to Offer 68 - recent common ancestor
Malicious attacks on mobile applications surge by 500%
WPF项目-初步了解数据绑定 binding
(2022 Nioke Duo School IV) D-Jobs (Easy Version) (3D prefix or)
Seleniu: Common operations on elements
Selenium:操作JS
2022.7.27好题选讲
vim configuration + ctag is as easy to read code as source insight
MySQL-DML language-database operation language-insert-update-delete-truncate
字符中的第一个唯一字符