【Python】【matplotlib】绘图

来源:互联网 发布:辐射4女角色捏脸数据 编辑:程序博客网 时间:2024/06/05 11:31

示例

import matplotlib.pyplot as pltimport numpy as npx=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 可以用LaTeXplt.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 npimport matplotlib.pyplot as pltdef func1(x):    return 0.6 * x + 0.3def func2(x):    return 0.4 * x * x + 0.1 * x + 0.2def 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) + xlx = 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 transformstrans = 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) / 2ym = (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 pltimport numpy as npx = 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 fontManagerfontManager.ttflist
  1. 系统自带字体的展示
import osfrom os import pathfrom matplotlib.font_manager import fontManagerimport matplotlib.pyplot as pltfig=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.05fonts = [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.05plt.show()

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

保存

plt.savefig('test.png',dpi=120)
原创粉丝点击