莫烦python简历_Matplotlib画图教程
目录
1 Matplotlib 简介
-----1.1 为什么用Matplotlib?
-----1.2 Matplotlib 安装
2 基本使用
-----2.1 基本用法
-----2.2 figure 图像
-----2.3 设置坐标轴1
-----2.4 设置坐标轴2
-----2.5 Legend 图例
-----2.6 Annotation 标注
-----2.7 tick 能见度
3 画图种类
-----3.1 Scatter 散点图
-----3.2 Bar 柱状图
-----3.3 Contours 等高线图
-----3.4 Image 图片
-----3.5 3D 数据
4 多图合并显示
-----4.1 Subplot 多合一显示
-----4.2 Subplot 分格显示
-----4.3 图中图
-----4.4 次坐标轴
5 动画
-----5.1 Animation 动画
****************************************本文参考****************************************Matplotlib 画图 | 莫烦Pythonmofanpy.com
*****************************************************************************************
1 Matplotlib 简介
1.1 为什么用Matplotlib?
Matplotlib是一个非常强大的Python画图工具,可以画出美丽的线图、散点图、等高线图、条形图、柱状图、3D图形,甚至是图形动画等等。
1.2 Matplotlib 安装
打开Pycharm,点击菜单上的“file”,再点击“setting”,选中你的项目,选中其下的“Project Interpreter”。出现界面后,点击最右边的“+”。出现界面后,搜索matplotlib,选中,选择版本,点击“Install Package”进行下载。
2 基本使用
2.1 基本用法
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x+1
plt.plot(x, y)
plt.show()
得到
2.2 figure 图像
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=3, linestyle='--')
plt.show()
得到
2.3 设置坐标轴1
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal\ \alpha$', r'$good$', r'$really\ good$'])
plt.show()
得到
2.4 设置坐标轴2
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal\ \alpha$', r'$good$', r'$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()
得到
2.5 Legend 图例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal\ \alpha$', r'$good$', r'$really\ good$'])
l1, = plt.plot(x, y2, label='up')
l2, = plt.plot(x, y1, color='red', linewidth=1, linestyle='--', label='down')
plt.legend(handles = [l1, l2,], labels = ['aaa', 'bbb'], loc='best') #loc: lower right, upper left, etc.
plt.show()
得到
2.6 Annotation 标注
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0, y0, s=50, color='b')
plt.plot([x0, x0], [0, y0], 'k--', linewidth=2.5)
plt.annotate(r'$2x+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.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
plt.show()
得到
2.7 tick 能见度
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
plt.plot(x, y, linewidth=10, zorder=1) # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.show()
得到
3 画图种类
3.1 Scatter 散点图
import matplotlib.pyplot as plt
import numpy as np
n = 1024 # data size
X = np.random.normal(0, 1, n) # 每一个点的X值
Y = np.random.normal(0, 1, n) # 每一个点的Y值
T = np.arctan2(Y, X) # for color value
plt.scatter(X, Y, s=75, c=T, alpha=0.5)
plt.xlim(-1.5, 1.5)
plt.xticks(()) # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(()) # ignore yticks
plt.show()
得到
3.2 Bar 柱状图
import matplotlib.pyplot as plt
import numpy as np
n = 12
X = np.arange(n)
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='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
for x, y in zip(X, Y1):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x, -y - 0.05, '%.2f' % y, ha='center', va='top')
plt.xlim(-0.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
plt.show()
得到
3.3 Contours 等高线图
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
# the height function
return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 - y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
# use plt.contourf to filling contours
# X, Y and value for (X,Y) point
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
# use plt.contour to add contour lines
C = plt.contour(X, Y, f(X, Y), 8, colors='black')
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
得到
3.4 Image 图片
import matplotlib.pyplot as plt
import numpy as np
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper')
plt.colorbar(shrink=0.92)
plt.xticks(())
plt.yticks(())
plt.show()
得到
3.5 3D 数据
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
# X, Y value
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y) # x-y 平面的网格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), edgecolor='black')
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
ax.set_zlim(-2, 2)
plt.show()
得到
4 多图合并显示
4.1 Subplot 多合一显示
(1)样式一
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 2])
plt.subplot(223)
plt.plot([0, 1], [0, 3])
plt.subplot(224)
plt.plot([0, 1], [0, 4])
plt.show()
得到
(2)样式二
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 2])
plt.subplot(235)
plt.plot([0, 1], [0, 3])
plt.subplot(236)
plt.plot([0, 1], [0, 4])
plt.show()
得到
4.2 Subplot 分格显示
(1)样式一
import matplotlib.pyplot as plt
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2], [1, 2]) # 画小图
ax1.set_title('ax1_title') # 设置小图的标题
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=1)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2, colspan=1)
ax4 = plt.subplot2grid((3, 3), (2, 0), rowspan=1, colspan=1)
ax5 = plt.subplot2grid((3, 3), (2, 1), rowspan=1, colspan=1)
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
plt.show()
得到
(2)样式二
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :2])
ax3 = plt.subplot(gs[1:, 2])
ax4 = plt.subplot(gs[-1, 0])
ax5 = plt.subplot(gs[-1, -2])
plt.show()
得到
(3)样式三
import matplotlib.pyplot as plt
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout() # plt.tight_layout()表示紧凑显示图像
plt.show()
得到
4.3 图中图
import matplotlib.pyplot as plt
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意对y进行了逆序处理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
得到
4.4 次坐标轴
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-') # green, solid line
ax2.plot(x, y2, 'b--') # blue
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()
得到
5 动画
5.1 Animation 动画
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=True)
plt.show()
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
得到
莫烦python简历_Matplotlib画图教程相关推荐
- 莫烦Python教程之Pandas教程
''' Day 2 ''''''1.错误处理''' # try: # file = open('eeee.txt','r+') #以只读的形式打开一个文件'eeee',不能'r',要用'r+'---' ...
- 莫烦python简历_强化学习传说:第一章 模仿学习
Hello,大家好,这里是糖葫芦喵喵~! 经过了几个月的奋斗,大家是不是对炼丹已经有所体会了呢?从今天起我们要进入机器学习的一个非常引人注目的领域--强化学习(reinforcement learni ...
- 【莫烦Python】Matplotlib Python画图教程
目录 前言 1.基本使用 1.1 基本用法 1.2 figure图像 1.3 设置坐标轴1 1.4 设置坐标轴2 1.5 Legend图例 1.6 Annotation标注 1.7 tick能见度 2 ...
- 【莫烦Python】Matplotlib Python 画图教程 目录引导
1.[莫烦Python]matplotlib Python画图教程 Matplotlib基本用法 2.[莫烦Python]Matplotlib Python 画图教程 figure图像 3.[莫烦Py ...
- 【莫烦Python】Pandas教程
目录 前言 1.Pandas vs Numpy 2.基本介绍 3.选择数据 4.设置值 5.处理丢失的数据 6.pandas导入导出 7.pandas合并concat 8.pandas合并merge ...
- 【莫烦Python】Python 基础教程——学习笔记
文章目录 本笔记基于p1-p29[莫烦Python]Python 基础教程 大家可以根据代码内容和注释进行学习. 安装 我的:python3.8+anaconda+VS code print() pr ...
- 【莫烦Python】机器要说话 NLP 自然语言处理教程 W2V Transformer BERT Seq2Seq GPT 笔记
[莫烦Python]机器要说话 NLP 自然语言处理教程 W2V Transformer BERT Seq2Seq GPT 笔记 教程与代码地址 P1 NLP行业大佬采访 P2 NLP简介 P3 1. ...
- 【莫烦Python】Numpy教程
目录 前言 1.numpy属性 2.numpy的array创建 3.numpy的基础运算 4.numpy的基础运算2 5.numpy的索引 6.numpy的array合并 7.numpy的array分 ...
- 莫烦python教程部分代码
GitHub资源整理 莫烦python教程部分代码 莫烦python教程部分代码 整理了一部分莫烦Python教程中的代码,并对代码进行了详细的注释.由于莫烦大佬在做TensorFlow教程时使用的0 ...
最新文章
- 如何用Python读取Excel中图片?又如何用Python往Excel中写入图片?
- iptables高级应用实例
- java+读取source资源_如何从JavaJAR文件中读取资源文件?
- 音视频技术傻瓜版解析:带你解锁RTMP
- Huawei is developing a new future technology
- BZOJ2406矩阵——有上下界的可行流+二分答案
- 丁胖胖眼中的WINDOWS操作系统(一)
- 计算机数制和运算的一点总结.
- oj 小黑华丽的逆袭机会
- 2022下半年软考冲刺,这些资料就是45分通关密码
- UDA/语义分割/ICCV2021:Dual Path Learning for Domain Adaptation of Semantic Segmentation语义分割领域自适应的双路径学习
- spring cloud day(6) gateway网关
- 线上连锁线下整合的连锁电商架构 打造店店互推人人分销模式
- Bmob后端云的使用
- Entry name ‘META-INF/MANIFEST.MF‘ collided
- 2021.9.15 每日总结
- 0x01 - 前期信息收集
- DEBUG系列一:Dumpdebug_SAP刘梦_新浪博客
- Conflux人物志 | 元气满满的办事员小罗
- STM32 gcc编译环境搭建