打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python绘图总结(Matplotlib篇)之字体、文本及注释

学习https://matplotlib.org/gallery/index.html 记录,描述不一定准确,具体请参考官网

Matplotlib使用总结图

%matplotlib inlineimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号import pandas as pdimport numpy as np
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

字体

import osfrom matplotlib import font_manager as fm, rcParamsimport matplotlib.pyplot as pltfig, ax = plt.subplots()fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")prop = fm.FontProperties(fname=fpath)fname = os.path.split(fpath)[1]ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)ax.set_xlabel('This is the default font')plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

显示文本

# 显示数学文本t = np.arange(0.0, 2.0, 0.01)s = np.sin(2*np.pi*t)plt.plot(t,s)plt.title(r'$\alpha_i > \beta_i$', fontsize=20)plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',         fontsize=20)plt.xlabel('time (s)')plt.ylabel('volts (mV)')plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

import matplotlib.patches as patches# build a rectangle in axes coordsleft, width = .25, .5bottom, height = .25, .5right = left + widthtop = bottom + heightfig = plt.figure()ax = fig.add_axes([0,0,1,1])# axes coordinates are 0,0 is bottom left and 1,1 is upper rightp = patches.Rectangle(    (left, bottom), width, height,    fill=False, transform=ax.transAxes, clip_on=False    )ax.add_patch(p)ax.text(left, bottom, 'left top',        horizontalalignment='left',        verticalalignment='top',        transform=ax.transAxes)ax.text(left, bottom, 'left bottom',        horizontalalignment='left',        verticalalignment='bottom',        transform=ax.transAxes)ax.text(right, top, 'right bottom',        horizontalalignment='right',        verticalalignment='bottom',        transform=ax.transAxes)ax.text(right, top, 'right top',        horizontalalignment='right',        verticalalignment='top',        transform=ax.transAxes)ax.text(right, bottom, 'center top',        horizontalalignment='center',        verticalalignment='top',        transform=ax.transAxes)ax.text(left, 0.5*(bottom+top), 'right center',        horizontalalignment='right',        verticalalignment='center',        rotation='vertical',        transform=ax.transAxes)ax.text(left, 0.5*(bottom+top), 'left center',        horizontalalignment='left',        verticalalignment='center',        rotation='vertical',        transform=ax.transAxes)ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',        horizontalalignment='center',        verticalalignment='center',        fontsize=20, color='red',        transform=ax.transAxes)ax.text(right, 0.5*(bottom+top), 'centered',        horizontalalignment='center',        verticalalignment='center',        rotation='vertical',        transform=ax.transAxes)ax.text(left, top, 'rotated\nwith newlines',        horizontalalignment='center',        verticalalignment='center',        rotation=45,        transform=ax.transAxes)ax.set_axis_off()plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76

水印

from __future__ import print_functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt# Fixing random state for reproducibilitynp.random.seed(19680801)datafile = cbook.get_sample_data('logo2.png', asfileobj=False)print('loading %s' % datafile)im = image.imread(datafile)im[:, :, -1] = 0.5  # set the alpha channelfig, ax = plt.subplots()# ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7,mfc='orange')ax.grid()# 添加水印fig.figimage(im, 10, 10, zorder=3)plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
loading F:\Anaconda\lib\site-packages\matplotlib\mpl-data\sample_data\logo2.png
  • 1

注释

fig = plt.figure()fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')ax = fig.add_subplot(111)fig.subplots_adjust(top=0.85)ax.set_title('axes title')ax.set_xlabel('xlabel')ax.set_ylabel('ylabel')ax.text(3, 8, 'boxed italics text in data coords', style='italic',        bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik')ax.text(0.95, 0.01, 'colored text in axes coords',        verticalalignment='bottom', horizontalalignment='right',        transform=ax.transAxes,        color='green', fontsize=15)ax.plot([2], [1], 'o')# 注释ax.annotate('我是注释啦', xy=(2, 1), xytext=(3, 4),color='r',size=15,            arrowprops=dict(facecolor='g', shrink=0.05))ax.axis([0, 10, 0, 10])plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 10, 0.005)y = np.exp(-x/2.) * np.sin(2*np.pi*x)fig = plt.figure()ax = fig.add_subplot(111)# plt.subplot(221)   # 这种方式和上面的add_subplot() 定义相同,都是添加子图ax.plot(x, y)# 设置坐标轴刻度ax.set_xlim(0, 10)ax.set_ylim(-1, 1)xdata, ydata = 5, 0xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))bbox = dict(boxstyle="round", fc="0.8")arrowprops = dict(    arrowstyle = "->",    connectionstyle = "angle,angleA=0,angleB=90,rad=10")offset = 72ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),            (xdata, ydata), xytext=(-1.5*offset, offset), textcoords='offset points',            bbox=bbox, arrowprops=arrowprops)disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),            (xdisplay, ydisplay), xytext=(0.5*offset, -offset),            xycoords='figure pixels',            textcoords='offset points',            bbox=bbox, arrowprops=arrowprops)plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

fig = plt.figure()ax = fig.add_subplot(111, polar=True)  # 雷达图# ax = fig.add_subplot(111)  # 正常四方形r = np.arange(0,1,0.001)theta = 2 * 2*np.pi * rline, = ax.plot(theta, r, color='#ee8d18', lw=3)ind = 800thisr, thistheta = r[ind], theta[ind]ax.plot([thistheta], [thisr], 'o')   # 画蓝点# 画注释箭头ax.annotate('a polar annotation',            xy=(thistheta, thisr),  # theta, radius            xytext=(0.05, 0.05),    # fraction, fraction            textcoords='figure fraction',            arrowprops=dict(facecolor='black', shrink=0.05),            horizontalalignment='left',            verticalalignment='bottom',            )plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Python图表绘制:matplotlib绘图库入门
Python学习
【数字的可视化:python画图之散点图sactter函数详解】
python数据分析之:绘图和可视化
Python绘制参数方程图
Matplotlib image图像处理
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服