In [1]:
%matplotlib inline
In [2]:
# https://blog.csdn.net/qq_34337272/article/details/79555544
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn
from datetime import datetime
In [3]:
## 根据坐标点绘制
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([3,5,7,6,2,6,10,15])
plt.plot(x,y,'r')# 折线 1 x 2 y 3 color
plt.plot(x,y,'g',lw=10)# 4 line w
# 折线 饼状 柱状
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([13,25,17,36,21,16,10,15])
plt.bar(x,y,0.2,alpha=1,color='b')# 5 color 4 透明度 3 0.9
plt.show()
In [4]:
x = np.linspace(-1, 1,66)
## 绘制y=2x+1函数的图像
y = 2 * x + 1
plt.plot(x, y)
plt.show()
## 绘制x^2函数的图像
y = x**2
plt.plot(x, y)
plt.show()
In [5]:
x = np.linspace(-1, 1, 50)
# figure 1
y1 = 2 * x + 1
plt.figure()
plt.plot(x, y1)
# figure 2
y2 = x**2
plt.figure()
plt.plot(x, y2)
# figure 3,指定figure的编号并指定figure的大小, 指定线的颜色, 宽度和类型
y2 = x**2
plt.figure(num = 5, figsize = (4, 4))
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
plt.show()
In [6]:
plt.cla() # 清除坐标
In [7]:
plt.clf() # 清除图
In [8]:
# 绘制普通图像
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
# 设置坐标轴的取值范围
plt.xlim((-1, 1))
plt.ylim((0, 3))
# 设置坐标轴的lable
# 标签里面必须添加字体变量:fontproperties='SimHei',fontsize=14。不然可能会乱码
plt.xlabel(u'这是x轴',fontproperties='SimHei',fontsize=14)
plt.ylabel(u'这是y轴',fontproperties='SimHei',fontsize=14)
plt.xticks(np.linspace(-1, 1, 5))
# 获取当前的坐标轴, gca = get current axis
ax = plt.gca()
# 设置右边框和上边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 设置x坐标轴为下边框
ax.xaxis.set_ticks_position('bottom')
# 设置y坐标轴为左边框
ax.yaxis.set_ticks_position('left')
# 设置x轴, y周在(0, 0)的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 设置坐标轴label的大小,背景色等信息
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor = 'green', edgecolor = 'None', alpha = 0.7))
plt.show()
In [9]:
import matplotlib.pyplot as plt
import numpy as np
# 绘制普通图像
x = np.linspace(-3, 3, 50)
y = 2 * x + 1
plt.figure()
plt.plot(x, y)
# 将上、右边框去掉
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 设置x轴的位置及数据在坐标轴上的位置
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
# 设置y轴的位置及数据在坐标轴上的位置
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 定义(x0, y0)点
x0 = 1
y0 = 2 * x0 + 1
# 绘制(x0, y0)点
plt.scatter(x0, y0, s = 50, color = 'blue')
# 绘制虚线
plt.plot([x0, x0], [y0, 0], 'k--', lw = 2.5)
# 绘制注解一
plt.annotate(r'$2 * x + 1 = %s$' % y0, xy = (x0, y0), xycoords = 'data',
xytext = (+30, -30), textcoords = 'offset points',
fontsize = 16, arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3, rad = .2'))
# 绘制注解二
plt.text(-3, 3, r'$Test\ text. \mu \sigma_i, \alpha_i$', fontdict = {'size': 16, 'color': 'red'})
plt.show()
In [10]:
# 数据个数
n = 1024
# 均值为0, 方差为1的随机数
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
# 计算颜色值
color = np.arctan2(y, x)
# 绘制散点图
sca = plt.scatter(x, y, s = 75, c = color, alpha = 0.5)
# 设置坐标轴范围
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))
# 不显示坐标轴的值
plt.xticks(())
plt.yticks(())
plt.show()
In [11]:
# 如何隐藏散点图中的点
x = np.arange(100)
y = np.random.rand(100)
mask = y > 0.5
plt.scatter(x[mask], y[mask])
Out[11]:
In [12]:
# 隐藏整个散点图
sca.set_visible(False)
In [13]:
# 数据数目
n = 10
x = np.arange(n)
# 生成数据, 均匀分布(0.5, 1.0)之间
y1 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
# 绘制柱状图, 向上
plt.bar(x, y1, facecolor = 'blue', edgecolor = 'white')
# 绘制柱状图, 向下
plt.bar(x, -y2, facecolor = 'green', edgecolor = 'white')
temp = zip(x, y2)
# 在柱状图上显示具体数值, ha水平对齐, va垂直对齐
for x, y in zip(x, y1):
plt.text(x + 0.05, y + 0.1, '%.2f' % y, ha = 'center', va = 'bottom')
for x, y in temp:
plt.text(x + 0.05, -y - 0.1, '%.2f' % y, ha = 'center', va = 'bottom')
# 设置坐标轴范围
plt.xlim(-1, n)
plt.ylim(-1.5, 1.5)
# 去除坐标轴
plt.xticks(())
plt.yticks(())
plt.show()
In [14]:
# 定义等高线高度函数
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)
# 数据数目
n = 256
# 定义x, y
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
# 生成网格数据
X, Y = np.meshgrid(x, y)
# 填充等高线的颜色, 8是等高线分为几部分
plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.hot)
# 绘制等高线
C = plt.contour(X, Y, f(X, Y), 8, colors = 'black')
# 绘制等高线数据
plt.clabel(C, inline = True, fontsize = 10)
# 去除坐标轴
plt.xticks(())
plt.yticks(())
plt.show()
In [15]:
# 定义图像数据
a = np.linspace(0, 1, 9).reshape(3, 3)
# 显示图像数据
plt.imshow(a, interpolation = 'nearest', cmap = 'bone', origin = 'lower')
# 添加颜色条
plt.colorbar()
# 去掉坐标轴
plt.xticks(())
plt.yticks(())
plt.show()
In [16]:
plt.figure()
# 绘制第一个图
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
# 绘制第二个图
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 1])
# 绘制第三个图
plt.subplot(2, 2, 3)
plt.plot([0, 1], [0, 1])
# 绘制第四个图
plt.subplot(2, 2, 4)
plt.plot([0, 1], [0, 1])
plt.show()
In [32]:
# 这种方式无法合并
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 4))
print(fig.get_figwidth(), fig.get_figheight())
axes[0,0].plot([0, 1], [0, 1], linestyle='--')
axes[0,1].plot([0, 1], [0, 1], 'ko--')
axes[1,0].plot([0, 1], [0, 1], color='k', marker='o', linestyle='--')
axes[1,1].plot([0, 1], [0, 1], color='b', linestyle='dashed')
axes[0,0].set_xticks(())
axes[0, 0].locator_params("x", nbins = 6)
from matplotlib.ticker import MultipleLocator
# axes[0, 0].xaxis.set_major_locator(MultipleLocator(20))
In [26]:
# 定义figure
plt.figure()
# figure分成3行3列, 取得第一个子图的句柄, 第一个子图跨度为1行3列, 起点是表格(0, 0)
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan = 3, rowspan = 1)
ax1.plot([0, 1], [0, 1])
ax1.set_title('Test')
# figure分成3行3列, 取得第二个子图的句柄, 第二个子图跨度为1行3列, 起点是表格(1, 0)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan = 2, rowspan = 1)
ax2.plot([0, 1], [0, 1])
# figure分成3行3列, 取得第三个子图的句柄, 第三个子图跨度为1行1列, 起点是表格(1, 2)
ax3 = plt.subplot2grid((3, 3), (1, 2), colspan = 1, rowspan = 1)
ax3.plot([0, 1], [0, 1])
# figure分成3行3列, 取得第四个子图的句柄, 第四个子图跨度为1行3列, 起点是表格(2, 0)
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan = 3, rowspan = 1)
ax4.plot([0, 1], [0, 1])
plt.show()
In [19]:
# 定义figure
fig = plt.figure()
# 定义数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# figure的百分比, 从figure 10%的位置开始绘制, 宽高是figure的80%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# 获得绘制的句柄
ax1 = fig.add_axes([left, bottom, width, height])
# 绘制点(x,y)
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('test')
# 嵌套方法一
# figure的百分比, 从figure 10%的位置开始绘制, 宽高是figure的80%
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
# 获得绘制的句柄
ax2 = fig.add_axes([left, bottom, width, height])
# 绘制点(x,y)
ax2.plot(x, y, 'r')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('part1')
# 嵌套方法二
plt.axes([bottom, left, width, height])
plt.plot(x, y, 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.title('part2')
plt.show()
In [20]:
# 打开交互模式
plt.ion()
# do some thing
# 显示前关掉交互模式
plt.ioff()
plt.show()
In [21]:
for item in ax2.collections :
item.remove()
del ax.collections[:]
plt.show()