【Python】【matplotlib】绘图

示例

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,6,1000)
y=np.sin(x)
z=np.cos(x**2)
plt.plot(x,y,label="$sin(x)$",color='red',linewidth=2)
#label 可以用LaTeX
plt.plot(x,z,'b--',label='$cos(x^2)$')

plt.xlabel('Time(s)')
plt.ylabel('Volt')
plt.title('Pyplot')
plt.ylim(-1.2,1.2)
plt.legend()

plt.show()

linestyle&marker可以搭配使用,例如’.-‘,例如’+–’

matplotlib.rcParams

区域

import numpy as np
import matplotlib.pyplot as plt


def func1(x):
    return 0.6 * x + 0.3


def func2(x):
    return 0.4 * x * x + 0.1 * x + 0.2


def find_curve_intersects(x, y1, y2):
    d = y1 - y2
    idx = np.where(d[:-1] * d[1:] <= 0)[0]
    xl, x2 = x[idx], x[idx + 1]
    d1, d2 = d[idx], d[idx + 1]
    return -d1 * (x2 - xl) / (d2 - d1) + xl


x = np.linspace(-3, 3, 100)
f1 = func1(x)
f2 = func2(x)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, f1)
ax.plot(x, f2)

x1, x2 = find_curve_intersects(x,f1, f2)
ax.plot(x1, func1(x1), "o")
ax.plot(x2, func1(x2), "o")

ax.fill_between(x, f1, f2, where=f1 > f2, facecolor='green', alpha=0.5)

from matplotlib import transforms

trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
ax.fill_between([x1, x2], 0, 1, transform=trans, alpha=0.1)

a = ax.text(0.05, 0.95, "intersection of two curves",
            transform=ax.transAxes,
            verticalalignment="top", fontsize=18,
            bbox={"facecolor": "red", "alpha": 0.4, "pad": 10}
            )

arrow = {"arrowstyle": "fancy,tail_width=0.6",
         "facecolor": "gray",
         "connectionstyle": "arc3,rad=-0.3"}

ax.annotate("intersection",
            xy=(x1, func1(x1)),
            xycoords="data",
            xytext=(0.05, 0.5),
            textcoords="axes fraction",
            arrowprops=arrow)

ax.annotate("intersection",
            xy=(x2, func1(x2)),
            xycoords="data",
            xytext=(0.05, 0.5),
            textcoords="axes fraction",
            arrowprops=arrow)

xm = (x1 + x2) / 2
ym = (func1(xm) - func2(xm)) / 2 + func2(xm)
o = ax.annotate("intersection area",
                xy=(xm, ym), xycoords="data",
                xytext=(30, -30),
                textcoords="offset points",
                bbox={"boxstyle": "round", "facecolor": (1.0, 0.7, 0.7), "edgecolor": "none"},
                fontsize=16,
                arrowprops={"arrowstyle": "->"}
                )

plt.show()

http://www.guofei.site/public/postimg2/matplotlib1.png‘>

涉及知识点:
1. ax.annotate(),详解见于这里
2. fill_between(),看代码容易理解
3. trans

多图表&多子图

  • plt.figure(1)可以转换当前的画布
  • plt.sca(ax1)转换到指定的axes
# 一个案例
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 10)

plt.figure(1)
ax1_211 = plt.subplot(221)
ax1_212 = plt.subplot(223)
ax1_122 = plt.subplot(122)

plt.figure(2)
ax2_211 = plt.subplot(211)
ax2_212 = plt.subplot(212)

plt.sca(ax1_211)
plt.plot(x, np.sin(x))
plt.sca(ax1_212)
plt.plot(x, np.cos(x))
plt.sca(ax1_122)
plt.plot(x, x)

plt.sca(ax2_211)
plt.plot(x, x)
plt.plot(x, -x)
plt.sca(ax2_212)
plt.plot(x, np.sin(x))

plt.show()

字体&汉字支持

  1. 查询系统自带的字体
from matplotlib.font_manager import fontManager
fontManager.ttflist
  1. 系统自带字体的展示
import os
from os import path
from matplotlib.font_manager import fontManager
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(8,7))
ax=fig.add_subplot(111)
plt.subplots_adjust(0,0,1,1,0,0)
plt.xticks([])
plt.yticks([])
x,y=0.05,0.05
fonts = [font.name for font in fontManager.ttflist if path.exists(font.fname) and os.stat(font.fname).st_size>1e6]
font = set(fonts)
dy = (1.0 - y) / (len(fonts) // 4 + (len(fonts)%4 != 0))

for font in fonts:
    t = ax.text(x, y + dy / 2, "中文字体",{'fontname':font, 'fontsize':14}, transform=ax.transAxes)
    ax.text(x, y, font, {'fontsize':12}, transform=ax.transAxes)
    x += 0.25
    if x >= 1.0:
        y += dy
        x = 0.05
plt.show()

http://www.guofei.site/public/postimg2/matplotlib.png‘>

保存

plt.savefig('test.png',dpi=120)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值