美文网首页
Python 全栈:画图练习

Python 全栈:画图练习

作者: you的日常 | 来源:发表于2020-12-09 10:45 被阅读0次

354 10行代码看matplotlib绘图基本原理

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
line,  = ax.plot([0,1], [0,1])
ax.set_title("a straight line ")
ax.set_xlabel("x label")
ax.set_ylabel("y label")
canvas.print_figure('chatpic1.jpg')

上面这段代码,至少构建了四个对象: fig( Figure 类), canvas( FigureCanvas 类), ax( Axes 类), line(Line2D 类)。

在 matplotlib 中:

  • 整个图像为一个Figure 对象
  • Figure 对象中可以包含一个或多个 Axes 对象
    • Axes对象 axes1 都是一个拥有自己坐标系统的绘图区域
    • AxesxAxis,yAxis,title,data构成
      • xAxis 由 XTick, Ticker 以及 label 构成
      • yAxis 由 YTick, Ticker 以及 label 构成
    • Axes 对象 axes2 也是一个拥有自己坐标系统的绘图区域
    • AxesxAxis,yAxis,title,data构成
      • xAxis 由 XTick, Ticker 以及 label 构成
      • yAxis 由 YTick, Ticker 以及 label 构成

如下图所示:

image

canvas 对象,代表真正进行绘图的后端(backend)

ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]),分别表示:图形区域的左边界距离 figure 左侧 10% ,底部 10%,宽度和高度都为整个 figure 宽度和高度的 80%.

在具备这些绘图的基本理论知识后,再去使用 matplotlib 库就会顺手很多。

355 绘制折线图

导入

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

数据

x = np.linspace(0, 5, 10) 
y = x ** 2  

折线图

plt.plot(x, y) 
plt.show() 

image

356 调整线条颜色

plt.plot(x, y, 'r') 
plt.show() 

image

357 修改线型

plt.plot(x, y, 'r--') 
plt.show() 

image
plt.plot(x, y, 'g-*') 
plt.show() 

image

358 修改标题

plt.plot(x, y, 'r-*') 
plt.title('title')  
plt.show() 

image

359 添加 x,y轴 label和title

plt.plot(x, y, 'r-*') 
plt.title('title') 
plt.xlabel('x') 
plt.ylabel('y')
plt.show() 

image

360 添加 text 文本

plt.plot(x, y, 'r--') 
plt.text(1.5,10,'y=x*x')

image

361 添加 annotate 注解

plt.plot(x, y, 'r') 
plt.annotate('this is annotate',xy=(3.5,12),xytext=(2,16),arrowprops={'headwidth':10,'facecolor':'r'})

image

362 matplotlib配置显示中文

相关文章

网友评论

      本文标题:Python 全栈:画图练习

      本文链接:https://www.haomeiwen.com/subject/zjkdrktx.html