py- 绘图(3)

目录

  • Numpy & Matplotlib、格式字符串、中文
  • Demo
    由简到繁,绘制完善正弦余弦图。
  • 图象、子图、坐标轴
    图象即画布;子图即在画布上分区绘图;坐标轴与子图类似,但可以随意安放图形位置。


Numpy & Matplotlib、格式字符串、中文

Matplotlib与Numpy一起使用,提供了一种有效的MatLab替代方案。也可以与图形工具包一起使用,如PyQt和wxPython。

x = np.arange(1, 11)
y = 2 * x + 5
plt.title('Matplotlib demo')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.plot(x, y)
plt.show()

py- 绘图(3)_第1张图片

x = np.arange(1, 11)
y = 2 * x + 5

# 可以使用系统字体进行修改,打印出系统字典并选择
# import matplotlib
# a = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
# 
plt.rcParams['font.family']=['cmtt10']

plt.title('Matplotlib demo')
plt.xlabel('X axis')
plt.ylabel('Y axis')

# 作为线性图的替代,可以添加格式字符串来显示离散值
# plt.plot(x, y, 'b-')  # 默认:蓝色、实线
# 'ro' 红色,圆点
#
plt.plot(x, y, 'ro')
plt.show()

py- 绘图(3)_第2张图片
以下是线型字符:

字符 描述
'-' 实线样式
'--' 短横线样式
'-.' 点划线样式
':' 虚线样式
'.' 点标记
',' 像素标记
'o' 圆标记
'v' 倒三角标记
'^' 正三角标记
'1' 下箭头标记
'2' 上箭头标记
'3' 左箭头标记
'4' 右箭头标记
's' 正方形标记
'p' 五边形标记
'*' 星形标记
'h' 六边形标记 1
'H' 六边形标记 2
'+' 加号标记
'x' X 标记
'D' 菱形标记
'd' 窄菱形标记
'_' 水平线标记

以下是颜色的缩写:

字符 颜色
'b' 蓝色
'g' 绿色
'r' 红色
'c' 青色
'm' 品红色
'y' 黄色
'k' 黑色
'w' 白色

注:plt不支持中文,可以自己下载字体并手动加载。

import matplotlib

x = np.arange(1, 11)
y = 2 * x + 5

# fname = 下载文件绝对地址
zhfont = matplotlib.font_manager.FontProperties(fname=r'SimHei.ttf')

# plt.rcParams['font.family']=['cmtt10']
plt.title('Matplotlib 示例', fontproperties=zhfont)
plt.xlabel('X 轴', fontproperties=zhfont)
plt.ylabel('Y 轴', fontproperties=zhfont)
plt.plot(x, y, 'r')
plt.show()

py- 绘图(3)_第3张图片

Demo

先画简单的正余弦图,再逐渐完善

# 如修改过字体,负号无法正常显示,需先修改默认字体
# import matplotlib
# plt.rcParams['font.family'] = ['Arial']

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)

plt.plot(x, c)
plt.plot(x, s)

plt.show()

py- 绘图(3)_第4张图片

plt.figure(figsize=(8, 6), dpi=80)
plt.subplot(1, 1, 1)

plt.plot(x, c, color='r', linewidth=1, linestyle='-')  # 颜色 粗细
plt.plot(x, s, color='b', linewidth=1, linestyle='-')

plt.xlim(-4, 4)  # 上下限
plt.xticks(np.linspace(-4, 4, 9, endpoint=True))  # 轴标签

plt.ylim(-1, 1)
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))

plt.show()

py- 绘图(3)_第5张图片

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)

plt.figure(figsize=(8, 6), dpi=80)
plt.subplot(1, 1, 1)

plt.plot(x, c, color='r')
plt.plot(x, s, color='b')

xmin, xmax = x.min(), x.max()
dx = (xmax - xmin) * 0.02
plt.xlim(xmin - dx, xmax + dx)  # 优化曲线与边框交界
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])  # 使用LaTex,优化轴标签

ymin, ymax = c.min(), c.max()
dy = (ymax - ymin) * 0.02
plt.ylim(ymin - dy, ymax + dy)
plt.yticks([-1, 0, 1], [r'$-1$', r'$0$', r'$+1$'])

plt.show()

py- 绘图(3)_第6张图片

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)

plt.figure(figsize=(8, 6), dpi=80)
plt.subplot(1, 1, 1)

plt.plot(x, c, color='r', linewidth=1, linestyle='-', label='cosine')  # 标签:cosine
plt.plot(x, s, color='b', label='sine')

xmin, xmax = x.min(), x.max()
dx = (xmax - xmin) * 0.02
plt.xlim(xmin - dx, xmax + dx)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])

ymin, ymax = c.min(), c.max()
dy = (ymax - ymin) * 0.02
plt.ylim(ymin - dy, ymax + dy)
plt.yticks([-1, 0, 1], [r'$-1$', r'$0$', r'$+1$'])

ax = plt.gca()  # 获取轴
ax.spines['right'].set_color('none')  # 设置为无色
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')  # 设置 为x轴
ax.spines['bottom'].set_position(('data', 0))  # 交
ax.yaxis.set_ticks_position('left')  # 设置为y轴
ax.spines['left'].set_position(('data', 0)) 

plt.legend(loc=2)  # 图例

plt.show()

py- 绘图(3)_第7张图片

loc : int or string or pair of floats, default: ‘upper right’
The location of the legend. Possible codes are:
============================
Location String Location Code
============================
‘best’ 0
‘upper right’ 1
‘upper left’ 2
‘lower left’ 3
‘lower right’ 4
‘right’ 5
‘center left’ 6
‘center right’ 7
‘lower center’ 8
‘upper center’ 9
‘center’ 10
============================
Alternatively can be a 2-tuple giving x, y of the lower-left
corner of the legend in axes coordinates (in which case
bbox_to_anchor will be ignored).

图像、子图、坐标轴

  • 图像
    即画布,承载目标图形的所有元素。

  • 子图

plt.figure()

plt.subplot(2, 1, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, 'subplot(2, 1, 1)', ha='center', va='center', size=24, alpha=.5)

plt.subplot(2, 1, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, 'subplot(2, 1, 2)', ha='center', va='center')

plt.show()

py- 绘图(3)_第8张图片

 plt.figure()

plt.subplot(1, 2, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, 'subplot(1,2,1)', size=12, alpha=.5)

plt.subplot(1, 2, 2)
plt.xticks([])
plt.yticks([])

plt.show()

py- 绘图(3)_第9张图片

plt.figure()

plt.subplot(1, 3, 1)

plt.subplot(1, 3, 2)

plt.subplot(1, 3, 3)

plt.show()

py- 绘图(3)_第10张图片

plt.figure()

plt.subplot(2, 2, 1)
plt.xticks([])
plt.yticks([])
plt.text(.2, .2, 'subplot(2,2,1)', size=12, alpha=.5)

plt.subplot(2, 2, 2)
plt.xticks([])
plt.yticks([])
plt.text(.2, .2, 'subplot(2,2,2)', size=12, alpha=.5)

plt.subplot(2, 2, 3)
plt.xticks([])
plt.yticks([])
plt.text(.2, .2, 'subplot(2,2,3)')

plt.subplot(2, 2, 4)
plt.xticks([])
plt.yticks([])

plt.show()

py- 绘图(3)_第11张图片

import matplotlib.gridspec as gds

G = gds.GridSpec(3, 3)

ax1 = plt.subplot(G[0, :])
plt.xticks([])
plt.yticks([])
plt.text(.3, .3, 'G[0, :]', size=12, alpha=.5)

ax2 = plt.subplot(G[1, :-1])

ax3 = plt.subplot(G[2, :-1])

ax4 = plt.subplot(G[1:, 2])

plt.show()

py- 绘图(3)_第12张图片


  • 轴和子图的功能类似。但它可以放置在画布的任意位置。当需要在图中画小图的时候,很方便。
plt.axes([0.1, 0.1, .8, .8])
plt.text(.6, .8, 'axes([.1, .1, .8. .8])', size=12, alpha=.5)

plt.axes([.2, .2, .5, .5])

plt.show()

py- 绘图(3)_第13张图片

  • 附1. 菜鸟:Matplotlib教程

你可能感兴趣的:(数据分析,Py)