mirror of
https://github.com/Estom/notes.git
synced 2026-02-03 10:33:35 +08:00
matplotlib教程
This commit is contained in:
60
Python/matplotlab/学习教程/02配置属性列表.md
Normal file
60
Python/matplotlab/学习教程/02配置属性列表.md
Normal file
@@ -0,0 +1,60 @@
|
||||
# 属性配置
|
||||
|
||||
|
||||
## 线条风格linestyle
|
||||
|
||||
线条风格| 描述
|
||||
----|---
|
||||
‘-‘ |实线
|
||||
‘:’ |虚线
|
||||
‘–’ |破折线
|
||||
‘None’,’ ‘,’’ |什么都不画
|
||||
‘-.’ |点划线
|
||||
|
||||
## 线条标记marker
|
||||
|
||||
标记 | 描述
|
||||
----|----
|
||||
‘o’ |圆圈
|
||||
‘.’ |点
|
||||
‘D’ |菱形
|
||||
‘s’ |正方形
|
||||
‘h’ |六边形1
|
||||
‘*’ |星号
|
||||
‘H’ |六边形2
|
||||
‘d’ |小菱形
|
||||
‘_’ | 水平线
|
||||
‘v’ |一角朝下的三角形
|
||||
‘8’ |八边形
|
||||
‘<’ | 一角朝左的三角形
|
||||
‘p’ |五边形
|
||||
‘>’ |一角朝右的三角形
|
||||
‘,’ |像素
|
||||
‘^’ | 一角朝上的三角形
|
||||
‘+’ | 加号
|
||||
‘\ ‘ |竖线
|
||||
‘None’,’’,’ ‘ |无
|
||||
‘x’ | X
|
||||
|
||||
|
||||
## 颜色color
|
||||
|
||||
别名 | 颜色
|
||||
---|---
|
||||
b | 蓝色
|
||||
g |绿色
|
||||
r |红色
|
||||
y |黄色
|
||||
c |青色
|
||||
k |黑色
|
||||
m |洋红色
|
||||
w |白色
|
||||
|
||||
## 位置position
|
||||
|
||||
别名 | 位置
|
||||
--|--
|
||||
bottom | 底部
|
||||
top | 顶部
|
||||
left | 左边
|
||||
right | 右边
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 在这里的实例中,面向对象的方法与命令行的方式进行了混用,不提倡。首先运用好交互式命令行的方式进行绘图。
|
||||
|
||||
## 配置参数
|
||||
## 对象和参数
|
||||
|
||||
* axex: 设置坐标轴边界和表面的颜色、坐标刻度值大小和网格的显示
|
||||
* figure: 控制dpi、边界颜色、图形大小、和子区( subplot)设置
|
||||
@@ -16,56 +16,6 @@
|
||||
* xticks和yticks: 为x,y轴的主刻度和次刻度设置颜色、大小、方向,以及标签大小。
|
||||
|
||||
|
||||
## 线条风格
|
||||
|
||||
线条风格linestyle或ls | 描述
|
||||
----|---
|
||||
‘-‘ |实线
|
||||
‘:’ |虚线
|
||||
‘–’ |破折线
|
||||
‘None’,’ ‘,’’ |什么都不画
|
||||
‘-.’ |点划线
|
||||
|
||||
## 线条标记
|
||||
|
||||
标记maker | 描述
|
||||
----|----
|
||||
‘o’ |圆圈
|
||||
‘.’ |点
|
||||
‘D’ |菱形
|
||||
‘s’ |正方形
|
||||
‘h’ |六边形1
|
||||
‘*’ |星号
|
||||
‘H’ |六边形2
|
||||
‘d’ |小菱形
|
||||
‘_’ | 水平线
|
||||
‘v’ |一角朝下的三角形
|
||||
‘8’ |八边形
|
||||
‘<’ | 一角朝左的三角形
|
||||
‘p’ |五边形
|
||||
‘>’ |一角朝右的三角形
|
||||
‘,’ |像素
|
||||
‘^’ | 一角朝上的三角形
|
||||
‘+’ | 加号
|
||||
‘\ ‘ |竖线
|
||||
‘None’,’’,’ ‘ |无
|
||||
‘x’ | X
|
||||
|
||||
|
||||
## 颜色
|
||||
|
||||
别名 | 颜色
|
||||
---|---
|
||||
b | 蓝色
|
||||
g |绿色
|
||||
r |红色
|
||||
y |黄色
|
||||
c |青色
|
||||
k |黑色
|
||||
m |洋红色
|
||||
w |白色
|
||||
|
||||
|
||||
## 绘图步骤
|
||||
|
||||
```py
|
||||
@@ -81,9 +81,10 @@ ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].set_color('none')
|
||||
plt.show()
|
||||
```
|
||||
调整刻度及边框位置
|
||||
使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.(所有位置:top,bottom,both,default,none);使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data)
|
||||
|
||||
## 调整刻度及边框位置
|
||||
* 使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.(所有位置:top,bottom,both,default,none);使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data)
|
||||
```py
|
||||
plt.figure(num=3, figsize=(8, 5))
|
||||
plt.plot(x, y2)
|
||||
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
|
||||
@@ -97,9 +98,10 @@ ax.spines['top'].set_color('none')
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.spines['bottom'].set_position(('data', 0))
|
||||
plt.show()
|
||||
```
|
||||
|
||||
使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置:left.(所有位置:left,right,both,default,none) 使用.spines设置边框:y轴;使用.set_position设置边框位置:x=0的位置;(位置所有属性:outward,axes,data) 使用plt.show显示图像.
|
||||
|
||||
```py
|
||||
plt.figure(num=3, figsize=(8, 5))
|
||||
plt.plot(x, y2)
|
||||
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
|
||||
@@ -115,10 +117,10 @@ ax.spines['bottom'].set_position(('data', 0))
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
ax.spines['left'].set_position(('data',0))
|
||||
plt.show()
|
||||
|
||||
练一练
|
||||
小伙伴们,以上就是matplotlib的基本用法,是不是比较简单呢?现在,请根据上述所学内容,画出直线 y = x-1, 线型为虚线,线宽为1,纵坐标范围(-2,1),横坐标范围(-1,2),横纵坐标在(0,0)坐标点相交。横坐标的 [-1,-0.5,1] 分别对应 [bad, normal, good]。请一定自己尝试一番再看下面的答案噢~
|
||||
|
||||
```
|
||||
## 练一练
|
||||
* 小伙伴们,以上就是matplotlib的基本用法,是不是比较简单呢?现在,请根据上述所学内容,画出直线 y = x-1, 线型为虚线,线宽为1,纵坐标范围(-2,1),横坐标范围(-1,2),横纵坐标在(0,0)坐标点相交。横坐标的 [-1,-0.5,1] 分别对应 [bad, normal, good]。请一定自己尝试一番再看下面的答案噢~
|
||||
```py
|
||||
#答案
|
||||
x = np.linspace(-1, 2, 50)
|
||||
y = x - 1
|
||||
@@ -132,4 +134,5 @@ ax.spines['top'].set_color('none')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['left'].set_position(('data',0))
|
||||
ax.spines['bottom'].set_position(('data',0))
|
||||
plt.show()
|
||||
plt.show()
|
||||
```
|
||||
193
Python/matplotlab/学习教程/05图例和标注.md
Normal file
193
Python/matplotlab/学习教程/05图例和标注.md
Normal file
@@ -0,0 +1,193 @@
|
||||
# 图例和标注
|
||||
|
||||
## 基本用法
|
||||
本章知识点归纳如下:
|
||||
|
||||
1. 添加图例:plt.legend()
|
||||
|
||||
2. 画点:plt.scatter()
|
||||
|
||||
3. 添加标注:plt.annotate()
|
||||
|
||||
4. 添加注释:plt.text()
|
||||
|
||||
## 添加图例
|
||||
* matplotlib 中的 legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构。上次课我们了解到关于坐标轴设置方面的一些内容,代码如下:
|
||||
```py
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
x = np.linspace(-3, 3, 50)
|
||||
y1 = 2*x + 1
|
||||
y2 = x**2
|
||||
|
||||
plt.figure()
|
||||
#set x limits
|
||||
plt.xlim((-1, 2))
|
||||
plt.ylim((-2, 3))
|
||||
|
||||
# set new sticks
|
||||
new_sticks = np.linspace(-1, 2, 5)
|
||||
plt.xticks(new_sticks)
|
||||
# set tick labels
|
||||
plt.yticks([-2, -1.8, -1, 1.22, 3],
|
||||
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
|
||||
/opt/conda/lib/python3.5/site-packages/matplotlib/font_manager.py:278: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
|
||||
'Matplotlib is building the font cache using fc-list. '
|
||||
([<matplotlib.axis.YTick at 0x7f1352226780>,
|
||||
<matplotlib.axis.YTick at 0x7f13522260b8>,
|
||||
<matplotlib.axis.YTick at 0x7f135a628cf8>,
|
||||
<matplotlib.axis.YTick at 0x7f1352243860>,
|
||||
<matplotlib.axis.YTick at 0x7f1352239f28>],
|
||||
<a list of 5 Text yticklabel objects>)
|
||||
|
||||
```
|
||||
* 本节中我们将对图中的两条线绘制图例,首先我们设置两条线的类型等信息(蓝色实线与红色虚线),并且通过label参数为两条线设置名称。比如直线的名称就叫做 "linear line", 曲线的名称叫做 "square line"。当然,只是设置好名称并不能使我们的图例出现,要通过plt.legend()设置图例的显示。legend获取代码中的 label 的信息, plt 就能自动的为我们添加图例。
|
||||
```py
|
||||
# set line syles
|
||||
l1 = plt.plot(x, y1, label='linear line')
|
||||
l2 = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
|
||||
plt.legend()
|
||||
<matplotlib.legend.Legend at 0x7f134bf9ee10>
|
||||
```
|
||||
* 如果希望图例能够更加个性化,可通过以下方式更改:参数 loc 决定了图例的位置,比如参数 loc='upper right' 表示图例将添加在图中的右上角。 其中’loc’参数有多种,’best’表示自动分配最佳位置,其余的如下:
|
||||
```
|
||||
'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
|
||||
```
|
||||
```py
|
||||
l1 = plt.plot(x, y1, label='linear line')
|
||||
l2 = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
|
||||
plt.legend(loc='upper right')
|
||||
<matplotlib.legend.Legend at 0x7f134bf230f0>
|
||||
```
|
||||
* 同样可以通过设置 handles 参数来选择图例中显示的内容。首先,在上面的代码 plt.plot(x, y2, label='linear line') 和 plt.plot(x, y1, label='square line') 中用变量 l1 和 l2 分别存储起来,而且需要注意的是 l1, l2,要以逗号结尾, 因为plt.plot() 返回的是一个列表。然后将 l1,l2 这样的objects以列表的形式传递给 handles。另外,label 参数可以用来单独修改之前的 label 信息, 给不同类型的线条设置图例信息。
|
||||
```py
|
||||
l1, = plt.plot(x, y1, label='linear line')
|
||||
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
|
||||
plt.legend(handles=[l1,l2,], labels=['up','down'], loc='best')
|
||||
<matplotlib.legend.Legend at 0x7f134bdc0be0>
|
||||
```
|
||||
|
||||
## Annotation 标注
|
||||
* 当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法,
|
||||
* 一种是用 plt 里面的 annotate,
|
||||
* 一种是直接用 plt 里面的 text 来写标注。
|
||||
|
||||
* 标注出点(x0, y0)的位置信息。用plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5) 画出一条垂直于x轴的虚线。其中,[x0, x0,], [0, y0,] 表示在图中画一条从点 (x0,y0) 到 (x0,0) 的直线,'k--' 表示直线的颜色为黑色(black),线形为虚线。而 plt.scatter 函数可以在图中画点,此时我们画的点为 (x0,y0), 点的大小(size)为 50, 点的颜色为蓝色(blue),可简写为 b。
|
||||
```py
|
||||
plt.figure(num=1, figsize=(8, 5),)
|
||||
ax = plt.gca()
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].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))
|
||||
plt.plot(x, y,)
|
||||
|
||||
x0 = 1
|
||||
y0 = 2*x0 + 1
|
||||
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
|
||||
# set dot styles
|
||||
plt.scatter([x0, ], [y0, ], s=50, color='b')
|
||||
<matplotlib.collections.PathCollection at 0x7f134bc22860>
|
||||
```
|
||||
## 添加注释 annotate
|
||||
* 接下来我们就对(x0, y0)这个点进行标注。第一种方式就是利用函数 annotate(),其中 r'' %y0 代表标注的内容,可以通过字符串 %s 将 y0 的值传入字符串;参数xycoords='data' 是说基于数据的值来选位置, xytext=(+30, -30) 和 textcoords='offset points' 表示对于标注位置的描述 和 xy 偏差值,即标注位置是 xy 位置向右移动 30,向下移动30, arrowprops是对图中箭头类型和箭头弧度的设置,需要用 dict 形式传入。
|
||||
```py
|
||||
plt.figure(num=1, figsize=(8, 5),)
|
||||
ax = plt.gca()
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].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))
|
||||
plt.plot(x, y,)
|
||||
|
||||
x0 = 1
|
||||
y0 = 2*x0 + 1
|
||||
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
|
||||
# set dot styles
|
||||
plt.scatter([x0, ], [y0, ], s=50, color='b')
|
||||
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"))
|
||||
Text(30,-30,'$2x+1=3$')
|
||||
```
|
||||
|
||||
## 添加注释 text
|
||||
第二种注释方式是通过 text() 函数,其中 -3.7,3, 是选取text的位置, r'' 为 text 的内容,其中空格需要用到转字符 \ ,fontdict 设置文本字的大小和颜色。
|
||||
```py
|
||||
plt.figure(num=1, figsize=(8, 5),)
|
||||
ax = plt.gca()
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].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))
|
||||
plt.plot(x, y,)
|
||||
|
||||
x0 = 1
|
||||
y0 = 2*x0 + 1
|
||||
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
|
||||
# set dot styles
|
||||
plt.scatter([x0, ], [y0, ], s=50, color='b')
|
||||
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'})
|
||||
Text(-3.7,3,'$This\\ is\\ the\\ some\\ text. \\mu\\ \\sigma_i\\ \\alpha_t$')
|
||||
```
|
||||
## tick 能见度
|
||||
当图片中的内容较多,相互遮盖时,我们可以通过设置相关内容的透明度来使图片更易于观察,也即是通过本节中的bbox参数设置来调节图像信息.首先参考之前的例子, 我们先绘制图像基本信息:
|
||||
```
|
||||
x = np.linspace(-3, 3, 50)
|
||||
y = 0.1*x
|
||||
|
||||
plt.figure()
|
||||
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
|
||||
plt.plot(x, y, linewidth=10, zorder=1)
|
||||
plt.ylim(-2, 2)
|
||||
ax = plt.gca()
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].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))
|
||||
```
|
||||
* 然后对被遮挡的图像调节相关透明度,本例中设置 x轴 和 y轴 的刻度数字进行透明度设置。其中label.set_fontsize(12)重新调节字体大小,bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度. 最终结果如下:
|
||||
```py
|
||||
plt.plot(x, y, linewidth=10, zorder=1)
|
||||
plt.ylim(-2, 2)
|
||||
ax = plt.gca()
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].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)
|
||||
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
|
||||
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
|
||||
plt.show()
|
||||
```
|
||||
175
Python/matplotlab/学习教程/06各类图形.md
Normal file
175
Python/matplotlab/学习教程/06各类图形.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# 不同图形
|
||||
|
||||
## 基本用法
|
||||
本章知识点归纳如下:
|
||||
|
||||
1. 散点图:plt.scatter()
|
||||
|
||||
2. 柱状图:plt.bar()
|
||||
|
||||
3. 等高线图:plt.contourf()
|
||||
|
||||
4. 在等高线图中增加label:plt.clabel()
|
||||
|
||||
5. 矩阵画图:plt.imshow()
|
||||
|
||||
6. 在随机矩阵图中增加colorbar:plt.colorbar()
|
||||
|
||||
## 散点图
|
||||
|
||||
* 首先,先引入matplotlib.pyplot简写作plt,再引入模块numpy用来产生一些随机数据。
|
||||
|
||||
1. 数据生成
|
||||
生成1024个呈标准正态分布的二维数据组 (平均数是0,方差为1) 作为一个数据集,并图像化这个数据集。每一个点的颜色值用T来表示:
|
||||
```py
|
||||
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
|
||||
```
|
||||
2. 画图:
|
||||
数据集生成完毕,现在来用 plt.scatter 画出这个点集,输入X和Y作为location,size=75,颜色为T,color map用默认值,透明度alpha 为 50%。 x轴显示范围定位(-1.5,1.5),并向xtick()函数传入空集()来隐藏x坐标轴,y轴同理:
|
||||
```py
|
||||
plt.scatter(X, Y, s=75, c=T, alpha=.5)
|
||||
|
||||
plt.xlim(-1.5, 1.5)
|
||||
plt.xticks(()) # ignore xticks
|
||||
plt.ylim(-1.5, 1.5)
|
||||
plt.yticks(()) # ignore yticks
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 柱状图
|
||||
* 柱状图是在数据分析过程中最为常用的图表,折线图和饼图能够表达的信息,柱状图都能够表达。在学术报告或工作场景下,大家应尽量使用柱状图来代替折线图与饼图。下面,我们就开始吧~
|
||||
|
||||
1. 数据生成:
|
||||
首先生成画图数据,向上向下分别生成2组数据,X为0到11的整数 ,Y是相应的均匀分布的随机数据。
|
||||
|
||||
2. 画图:
|
||||
使用的函数是plt.bar,参数为X和Y,X代表横坐标,即柱形的位置,Y代表纵坐标,即柱形的高度。
|
||||
```py
|
||||
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)
|
||||
plt.bar(X, -Y2)
|
||||
|
||||
plt.xlim(-.5, n)
|
||||
plt.xticks(())
|
||||
plt.ylim(-1.25, 1.25)
|
||||
plt.yticks(())
|
||||
|
||||
plt.show()
|
||||
```
|
||||
3. 修改颜色和数据标签
|
||||
如果小伙伴们想要改变柱状图的颜色,并且希望每个柱形上方能够显示该项数值该怎么做呢?我们可以用 plt.bar 函数中的facecolor参数设置柱状图主体颜色,用edgecolor参数设置边框颜色;而函数 plt.text 可以帮助我们在柱体上方(下方)加上数值:用%.2f保留两位小数,用ha='center'设置横向居中对齐,用va='bottom'设置纵向底部(顶部)对齐。
|
||||
```py
|
||||
plt.bar(X, +Y1, facecolor='#FFCCCC', edgecolor='white')
|
||||
plt.bar(X, -Y2, facecolor='#6699CC', edgecolor='white')
|
||||
|
||||
for x, y in zip(X, Y1):
|
||||
# ha: horizontal alignment
|
||||
# va: vertical alignment
|
||||
plt.text(x, y , '%.2f' % y, ha='center', va='bottom')
|
||||
|
||||
for x, y in zip(X, Y2):
|
||||
# ha: horizontal alignment
|
||||
# va: vertical alignment
|
||||
plt.text(x, -y , '%.2f' % y, ha='center', va='top')
|
||||
```
|
||||
## 等高线图
|
||||
1. 数据生成
|
||||
数据集即三维点 (x,y) 和对应的高度值,共有256个点。高度值使用一个 height function f(x,y) 生成。 x, y 分别是在区间 [-3,3] 中均匀分布的256个值,并用meshgrid在二维平面中将每一个x和每一个y分别对应起来,编织成栅格:
|
||||
```py
|
||||
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)
|
||||
```
|
||||
2. 画图:
|
||||
接下来进行颜色填充。使用函数plt.contourf把颜色加进去,位置参数分别为:X, Y, f(X,Y)。8代表等高线的密集程度,这里被分为10个部分。如果是0,则图像被一分为二。透明度为0.75,并将 f(X,Y) 的值对应到color map的RdBu组中寻找对应颜色。大家可能并不能直观理解 colormap ,它可以将颜色和数字进行映射。如果暂时不能理解的话也没有关系,我们可以将其想象成matplotlib为我们提供的配色方案,大家可以查看此链接选择自己喜欢的配色方案应用在自己的图上。
|
||||
```
|
||||
# use plt.contourf to filling contours
|
||||
# X, Y and value for (X,Y) point
|
||||
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.RdBu)
|
||||
<matplotlib.contour.QuadContourSet at 0x7f79c1734b38>
|
||||
```
|
||||
接下来进行等高线绘制。使用plt.contour函数划线。位置参数为:X, Y, f(X,Y)。颜色选黑色,线条宽度选0.5。现在的结果如下图所示,只有颜色和线条,还没有数值Label:
|
||||
```
|
||||
# use plt.contour to add contour lines
|
||||
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.RdBu)
|
||||
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
|
||||
/opt/conda/lib/python3.5/site-packages/matplotlib/contour.py:960: UserWarning: The following kwargs were not used by contour: 'linewidth'
|
||||
s)
|
||||
```
|
||||
3. 添加高度数字:
|
||||
最后我们要通过 plt.clabel() 在等高线上加入高度数值,即加入Label,其中参数 inline 控制是否将 Label 画在线里面,fontsize 设置字体大小为10。并将坐标轴隐藏:
|
||||
```
|
||||
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.RdBu)
|
||||
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
|
||||
plt.clabel(C, inline=True, fontsize=10)
|
||||
plt.xticks(())
|
||||
plt.yticks(())
|
||||
/opt/conda/lib/python3.5/site-packages/matplotlib/contour.py:960: UserWarning: The following kwargs were not used by contour: 'linewidth'
|
||||
s)
|
||||
([], <a list of 0 Text yticklabel objects>)
|
||||
```
|
||||
|
||||
## 随机矩阵画图
|
||||
* 这一节我们讲解怎样在matplotlib中打印出图像。这里我们打印出的是纯粹的数字,而非自然图像。
|
||||
|
||||
1. 数据生成
|
||||
首先生成一个 3x3 的 2D-array ,也就是三行三列的格子,array 中的每个值经过colormap与一个颜色对应并填充在格子中
|
||||
```py
|
||||
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
|
||||
0.365348418405, 0.439599930621, 0.525083754405,
|
||||
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
|
||||
```
|
||||
2. 画图:
|
||||
我们之前选cmap的参数时用的是:cmap=plt.cmap.RdBu,而现在,我们可以直接用单引号传入参数。 origin='lower'代表的就是选择的原点的位置。而 interpolation 表示画图方式,从该链接可看到matplotlib官网上对于内插法的不同方法的描述。这里我们使用的是内插法中的 Nearest-neighbor 的方法,其他的方式也都可以随意取选。
|
||||
```py
|
||||
plt.imshow(a, interpolation='nearest', cmap='RdBu', origin='lower')
|
||||
<matplotlib.image.AxesImage at 0x7f79c1641b38>
|
||||
```
|
||||
3. 增加colorbar
|
||||
下面我们添加一个colorbar ,它可以为我们显示不同颜色的区块所对应的具体数值。其中shrink参数可以用来调整 colorbar 的长度,这里我们使colorbar的长度变短为原来的92%,这样我们2D图像就创建完毕了:
|
||||
```py
|
||||
plt.imshow(a, interpolation='nearest', cmap='RdBu', origin='lower')
|
||||
plt.colorbar(shrink=.92)
|
||||
|
||||
plt.xticks(())
|
||||
plt.yticks(())
|
||||
plt.show()
|
||||
```
|
||||
## 练一练
|
||||
现在,小伙伴们可以尝试用上述方法对豆瓣电影数据集进行分析。请根据数据集中的表格'电影影评.csv'画出电影星级分布图。横坐标为电影的评分星级,分别为1,2,3,4,5;纵坐标为该星级下的电影数量。 提示:使用value_counts()函数对不同星级的电影数量进行计算
|
||||
```py
|
||||
#答案:
|
||||
import pandas as pd
|
||||
data = pd.read_csv('/home/kesci/input/movie_douban/电影影评.csv')
|
||||
data = data[data['星级']<=5]
|
||||
data_distri = data['星级'].value_counts()
|
||||
/opt/conda/lib/python3.5/site-packages/IPython/core/interactiveshell.py:2785: DtypeWarning: Columns (12,13,14,15,16,17,18,19,20,21,22,23,24,25,28,33,36) have mixed types. Specify dtype option on import or set low_memory=False.
|
||||
interactivity=interactivity, compiler=compiler, result=result)
|
||||
plt.figure(figsize=(6,4))
|
||||
plt.bar(data_distri.index, data_distri.values)
|
||||
plt.ylim(0, 60000)
|
||||
#设置数值标签
|
||||
x = np.array(list(data_distri.index))
|
||||
y = np.array(list(data_distri.values))
|
||||
for a,b in zip(x,y):
|
||||
plt.text(a, b+500, '%.0f' % b, ha='center', va= 'bottom',fontsize=10)
|
||||
```
|
||||
253
Python/matplotlab/学习教程/07子图绘制.md
Normal file
253
Python/matplotlab/学习教程/07子图绘制.md
Normal file
@@ -0,0 +1,253 @@
|
||||
# 子图绘制
|
||||
|
||||
## 基本用法
|
||||
本章知识点归纳如下,我们可以通过这三种方法中的任一种实现多图:
|
||||
|
||||
1. plt.subplot()
|
||||
|
||||
2. plt.subplot2grid()
|
||||
|
||||
3. gridspec.GridSpec()
|
||||
|
||||
4. plt.subplots()
|
||||
|
||||
5. 图中图:fig.add_axes()
|
||||
|
||||
6. 次坐标轴:ax.twinx()
|
||||
|
||||
## Subplot 多合一显示
|
||||
1. 均匀图中图
|
||||
首先使用import导入matplotlib.pyplot模块, 并简写成plt。 使用plt.figure创建一个图像窗口.使用plt.subplot来创建小图。plt.subplot(2,2,1)表示将整个图像窗口分为2行2列, 当前位置为1. 使用plt.plot([0,1],[0,1])在第1个位置创建一个小图。plt.subplot(2,2,2)表示将整个图像窗口分为2行2列, 当前位置为2。使用plt.plot([0,1],[0,2])在第2个位置创建一个小图。plt.subplot(2,2,3)表示将整个图像窗口分为2行2列,当前位置为3。 plt.subplot(2,2,3)可以简写成plt.subplot(223), matplotlib同样可以识别。使用plt.plot([0,1],[0,3])在第3个位置创建一个小图。plt.subplot(224)表示将整个图像窗口分为2行2列, 当前位置为4。使用plt.plot([0,1],[0,4])在第4个位置创建一个小图。
|
||||
```py
|
||||
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. 不均匀图中图
|
||||
如果希望展示的小图的大小不相同, 应该怎么做呢? 以上面的4个小图为例, 如果把第1个小图放到第一行, 而剩下的3个小图都放到第二行。使用plt.subplot(2,1,1)将整个图像窗口分为2行1列, 当前位置为1。使用plt.plot([0,1],[0,1])在第1个位置创建一个小图。使用plt.subplot(2,3,4)将整个图像窗口分为2行3列, 当前位置为4。使用plt.plot([0,1],[0,2])在第4个位置创建一个小图。
|
||||
|
||||
这里需要解释一下为什么第4个位置放第2个小图。上一步中使用plt.subplot(2,1,1)将整个图像窗口分为2行1列, 第1个小图占用了第1个位置, 也就是整个第1行。这一步中使用plt.subplot(2,3,4)将整个图像窗口分为2行3列, 于是整个图像窗口的第1行就变成了3列, 也就是成了3个位置, 于是第2行的第1个位置是整个图像窗口的第4个位置。
|
||||
```PY
|
||||
plt.subplot(2,1,1)
|
||||
plt.plot([0,1],[0,1])
|
||||
|
||||
plt.subplot(2,3,4)
|
||||
plt.plot([0,1],[0,2])
|
||||
[<matplotlib.lines.Line2D at 0x7f06584b3f60>]
|
||||
```
|
||||
接着,使用plt.subplot(235)将整个图像窗口分为2行3列,当前位置为5。使用plt.plot([0,1],[0,3])在第5个位置创建一个小图。同上, 再创建plt.subplot(236).
|
||||
```PY
|
||||
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() # 展示
|
||||
```
|
||||
matplotlib 的 subplot 还可以是分格的,这里介绍三种方法同样也能达到 subplot() 函数的效果:subplot2grid、gridspec 和 subplots 。他们相比起普通的 subplot 会更加方便,在判断图的编号时不需要进行很复杂的考虑。
|
||||
|
||||
## subplot2grid
|
||||
使用plt.subplot2grid来创建第1个小图, (3,3)表示将整个图像窗口分成3行3列, (0,0)表示从第0行第0列开始作图,colspan=3表示列的跨度为3, rowspan=1表示行的跨度为1。colspan和rowspan缺省, 表示默认跨度为1。
|
||||
```PY
|
||||
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
|
||||
ax1.plot([1, 2], [1, 2]) # 画小图
|
||||
ax1.set_title('ax1_title') # 设置小图的标题
|
||||
Text(0.5,1,'ax1_title')
|
||||
```
|
||||
|
||||
使用plt.subplot2grid来创建第2个小图, (3,3)表示将整个图像窗口分成3行3列, (1,0)表示从第1行第0列开始作图,colspan=2表示列的跨度为2. 同上画出 ax3, (1,2)表示从第1行第2列开始作图,rowspan=2表示行的跨度为2. 再画一个 ax4 和 ax5, 使用默认 colspan, rowspan。使用ax4.scatter创建一个散点图, 使用 ax4.setxlabel 和 ax4.setylabel 来对x轴和y轴命名。这样,我们就通过 subplot2grid() 完成了一张不均匀图中图。 细心的小伙伴可能可以注意到,在第一章我们设置标题与坐标轴时,使用的是plt.title()这样的语句,针对小图 ax ,我们的设置前都要加上 'set'。
|
||||
```PY
|
||||
plt.figure(figsize=(8, 6))
|
||||
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
|
||||
ax1.plot([1, 2], [1, 2]) # 画小图
|
||||
ax1.set_title('ax1_title') # 设置小图的标题
|
||||
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
|
||||
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
|
||||
ax4 = plt.subplot2grid((3, 3), (2, 0))
|
||||
ax5 = plt.subplot2grid((3, 3), (2, 1))
|
||||
ax4.scatter([1, 2], [2, 2])
|
||||
ax4.set_xlabel('ax4_x')
|
||||
ax4.set_ylabel('ax4_y')
|
||||
Text(0,0.5,'ax4_y')
|
||||
```
|
||||
## gridspec
|
||||
gridspec 同样能帮助我们画出前文的图,个人觉得 gridspec 的使用是最为方便的,因为它允许我们使用索引的方式指定小图的大小和位置。首先,利用import导入matplotlib.pyplot模块, 并简写成plt. 利用import导入matplotlib.gridspec, 并简写成gridspec.
|
||||
```PY
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.gridspec as gridspec
|
||||
/opt/conda/lib/python3.5/site-packages/matplotlib/font_manager.py:278: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
|
||||
'Matplotlib is building the font cache using fc-list. '
|
||||
```
|
||||
使用plt.figure()创建一个图像窗口, 使用gridspec.GridSpec将整个图像窗口分成3行3列.使用plt.subplot来作图, gs[0, :]表示这个图占第0行和所有列, gs[1, :2]表示这个图占第1行和第2列前的所有列, gs[1:, 2]表示这个图占第1行后的所有行和第2列, gs[-1, 0]表示这个图占倒数第1行和第0列, gs[-1, -2]表示这个图占倒数第1行和倒数第2列.
|
||||
```PY
|
||||
plt.figure(figsize=(8, 8))
|
||||
gs = gridspec.GridSpec(3, 3)
|
||||
|
||||
ax6 = plt.subplot(gs[0, :])
|
||||
ax7 = plt.subplot(gs[1, :2])
|
||||
ax8 = plt.subplot(gs[1:, 2])
|
||||
ax9 = plt.subplot(gs[-1, 0])
|
||||
ax10 = plt.subplot(gs[-1, -2])
|
||||
```
|
||||
|
||||
## subplots
|
||||
subplots 不同于 subplot, 它允许我们将图像窗口集合在一起表示。请看下面的代码:
|
||||
|
||||
首先,使用plt.subplots建立一个2行2列的图像窗口,sharex=True表示共享x轴坐标, sharey=True表示共享y轴坐标. ((ax11, ax12), (ax13, ax14))表示第1行从左至右依次放ax11和ax12, 第2行从左至右依次放ax13和ax14.接着使用ax11.scatter创建一个散点图.
|
||||
```
|
||||
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
|
||||
ax11.scatter([1,2], [1,2])
|
||||
<matplotlib.collections.PathCollection at 0x7f6180777ef0>
|
||||
```
|
||||
plt.tight_layout()表示紧凑显示图像, plt.show()表示显示图像.
|
||||
```
|
||||
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
|
||||
ax11.scatter([1,2], [1,2])
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 图中图
|
||||
接下来我们来介绍 matplotlib 里一个很有意思的功能,叫做图中图(plot in plot)。通过它,我们可以在大图中嵌入小图。
|
||||
|
||||
1. 生成数据
|
||||
```
|
||||
# 导入pyplot模块
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# 创建数据
|
||||
x = [1, 2, 3, 4, 5, 6, 7]
|
||||
y = [1, 3, 4, 2, 5, 8, 6]
|
||||
<Figure size 432x288 with 0 Axes>
|
||||
```
|
||||
2. 绘制大图
|
||||
首先确定大图左下角的位置以及宽高:
|
||||
|
||||
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
|
||||
注意,4个值都是占整个figure窗口的百分比。在这里,假设figure的大小是10x10,那么大图就被包含在由(1, 1)开始,宽8,高8的坐标系内。在klab上大家可能并不能理解figure的窗口大小,因为我们的图片会直接在代码下方显示,但对于其他平台,会出现弹出图片窗口的情况,这里的 figure 大小指的就是弹出窗口的大小。
|
||||
|
||||
接着,我们将大图坐标系添加到 figure 中,颜色为 r(red),取名为 title:
|
||||
```
|
||||
fig = plt.figure()
|
||||
|
||||
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')
|
||||
Text(0.5,1,'title')
|
||||
```
|
||||
3.绘制小图
|
||||
接着,我们来绘制左上角的小图,步骤和绘制大图一样,注意坐标系位置和大小的改变:
|
||||
```PY
|
||||
fig = plt.figure()
|
||||
|
||||
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')
|
||||
Text(0.5,1,'title inside 1')
|
||||
```
|
||||
最后,我们再来绘制右下角的小图。这里我们采用一种更简单方法,即直接往plt里添加新的坐标系:
|
||||
```PY
|
||||
fig = plt.figure()
|
||||
|
||||
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()
|
||||
```
|
||||
## 次坐标轴
|
||||
有时候我们会用到次坐标轴,即在同个图上有第2个y轴存在。这件事同样可以用matplotlib做到,而且很简单。首先,我们做一些准备工作:
|
||||
|
||||
1. 数据生成:
|
||||
```PY
|
||||
x = np.arange(0, 10, 0.1)
|
||||
y1 = 0.05 * x**2
|
||||
y2 = -1 * y1
|
||||
```
|
||||
2. 设置两个坐标系并画图:
|
||||
可以看到,y2和y1是互相倒置的。所以,我们先获取figure默认的坐标系 ax1;然后对ax1调用twinx()方法,生成如同镜面效果后的ax2;最后接着进行绘图, 将 y1, y2 分别画在 ax1, ax2 上:
|
||||
```PY
|
||||
fig, ax1 = plt.subplots()
|
||||
ax2 = ax1.twinx()
|
||||
|
||||
ax1.plot(x, y1, 'g-') # green, solid line
|
||||
ax1.set_xlabel('X data')
|
||||
ax1.set_ylabel('Y1 data', color='g')
|
||||
ax2.plot(x, y2, 'b-') # blue
|
||||
ax2.set_ylabel('Y2 data', color='b')
|
||||
Text(0,0.5,'Y2 data')
|
||||
```
|
||||
练一练
|
||||
相信通过本章的学习小伙伴们已经能够进行多图合并显示了,下面,请选择以上任意一种方法,画出3个函数:y = x; y = x^2; y = 0.01*x - 0.01
|
||||
```
|
||||
#参考答案:
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.gridspec as gridspec
|
||||
import numpy as np
|
||||
|
||||
x = np.linspace(-3, 3, 50)
|
||||
y1 = x
|
||||
y2 = x**2
|
||||
y3 = 0.01*x - 0.01
|
||||
|
||||
plt.figure(figsize=(8, 8))
|
||||
gs = gridspec.GridSpec(2, 2)
|
||||
|
||||
ax1 = plt.subplot(gs[0, 0])
|
||||
ax2 = plt.subplot(gs[0, 1])
|
||||
ax3 = plt.subplot(gs[1, :])
|
||||
|
||||
ax1.plot(x,y1)
|
||||
ax2.plot(x,y2)
|
||||
ax3.plot(x,y3)
|
||||
[<matplotlib.lines.Line2D at 0x7f6180086e48>]
|
||||
```
|
||||
129
Python/matplotlab/学习教程/083D与动画.md
Normal file
129
Python/matplotlab/学习教程/083D与动画.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# 3D与动画
|
||||
## 基本方法
|
||||
本章知识点归纳如下:
|
||||
|
||||
1. 创建3D图:ax = Axes3D(fig)
|
||||
|
||||
2. 画出3D图:ax.plot_surface()
|
||||
|
||||
3. 投影:ax.contourf()
|
||||
|
||||
4. 动画:animation.FuncAnimation()
|
||||
|
||||
## 3D作图
|
||||
首先在进行 3D Plot 时除了导入 matplotlib ,还要额外添加一个模块,即 Axes 3D 3D 坐标轴显示,并且之后要先定义一个图像窗口,在窗口上添加3D坐标轴,显示成下图:
|
||||
```py
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
|
||||
fig = plt.figure()
|
||||
ax = Axes3D(fig)
|
||||
```
|
||||
接下来给进 X 和 Y 值,并将 X 和 Y 编织成栅格。每一个(X, Y)点对应的高度值我们用下面这个函数来计算:
|
||||
```py
|
||||
# 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)
|
||||
```
|
||||
做出一个三维曲面,并将一个 colormap rainbow 填充颜色,之后将三维图像投影到 XY 平面上做一个等高线图。其中,rstride 和 cstride 分别代表 row 和 column 的跨度。跨度越小,图形上的网格越密集,实际画出的 plot 3D 图像会如下图所示:
|
||||
```py
|
||||
fig = plt.figure()
|
||||
ax = Axes3D(fig)
|
||||
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
|
||||
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7fcec6cf8320>
|
||||
```
|
||||
|
||||
## 投影
|
||||
有时候我们在观察3D图形时,可能需要图形映射到平面中来观察。还记得之前学习过的等高线图吗,它可以帮助我们对3D图像进行投影。下面代码为添加 XY 平面的等高线,如果 zdir 选择了x,那么效果将会是对于 XZ 平面的投影,而调整offset可以调整投影出现的位置,整体效果如下:
|
||||
```py
|
||||
fig = plt.figure()
|
||||
ax = Axes3D(fig)
|
||||
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
|
||||
ax.contourf(X, Y, Z, zdir='z', offset=-1, cmap=plt.get_cmap('rainbow'))
|
||||
<matplotlib.contour.QuadContourSet at 0x7fcec4b6aba8>
|
||||
```
|
||||
如果 zdir 选择了x,那么效果将会是对于 XZ 平面的投影,效果如下:
|
||||
```py
|
||||
fig = plt.figure()
|
||||
ax = Axes3D(fig)
|
||||
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
|
||||
ax.contourf(X, Y, Z, zdir='x', offset=-4, cmap=plt.get_cmap('rainbow'))
|
||||
<matplotlib.contour.QuadContourSet at 0x7fcec4919a90>
|
||||
```
|
||||
## Animation 动画
|
||||
最后,matplotlib还为我们提供了动画的接口。我们将使用其中一种方式 function animation 来为大家讲解,具体可参考matplotlib animation api。下面,我们就开始吧!
|
||||
|
||||
1. 导入动画库并定义方程
|
||||
我们的数据是一个0~2π内的正弦曲线:
|
||||
```
|
||||
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))
|
||||
```
|
||||
2. 构造动画函数与帧函数:
|
||||
接着,构造自定义动画函数animate,用来更新每一帧上各个x对应的y坐标值,参数表示第i帧;然后,构造开始帧函数init:
|
||||
```
|
||||
def animate(i):
|
||||
line.set_ydata(np.sin(x + i/10.0))
|
||||
return line,
|
||||
def init():
|
||||
line.set_ydata(np.sin(x))
|
||||
return line,
|
||||
```
|
||||
3. 参数设置:
|
||||
接下来,我们调用FuncAnimation函数生成动画。参数说明:
|
||||
|
||||
1. fig 进行动画绘制的figure
|
||||
|
||||
2. func 自定义动画函数,即传入刚定义的函数animate
|
||||
|
||||
3. frames 动画长度,一次循环包含的帧数
|
||||
|
||||
4. init_func 自定义开始帧,即传入刚定义的函数init
|
||||
|
||||
5. interval 更新频率,以ms计
|
||||
|
||||
6. lit 选择更新所有点,还是仅更新产生变化的点。应选择True,但mac用户请选择False,否则无法显示动画
|
||||
|
||||
(因为平台的不兼容问题,请klab暂时无法进行动画的演示,请大家在自己的电脑上尝试进行动画作图吧~)
|
||||
```py
|
||||
fig, ax = plt.subplots()
|
||||
line, = ax.plot(x, np.sin(x))
|
||||
|
||||
ani = animation.FuncAnimation(fig=fig,
|
||||
func=animate,
|
||||
frames=100,
|
||||
init_func=init,
|
||||
interval=20,
|
||||
blit=True)
|
||||
plt.show()
|
||||
```
|
||||
当然,你也可以将动画以mp4格式保存下来,但首先要保证你已经安装了ffmpeg 或者mencoder
|
||||
```
|
||||
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
|
||||
```
|
||||
## 练一练
|
||||
请大家根据之前所学的3D图画法画出3D数据 z = (x + y)^2, 并利用等高线图对其进行投影。
|
||||
```
|
||||
#参考答案:
|
||||
X = np.arange(-4, 4, 0.25)
|
||||
Y = np.arange(-4, 4, 0.25)
|
||||
X, Y = np.meshgrid(X, Y)
|
||||
Z = (X + Y)**2
|
||||
|
||||
fig = plt.figure()
|
||||
ax = Axes3D(fig)
|
||||
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
|
||||
ax.contourf(X, Y, Z, zdir='x', offset=-4, cmap=plt.get_cmap('rainbow'))
|
||||
<matplotlib.contour.QuadContourSet at 0x7fcec4416400>
|
||||
```
|
||||
19
Python/matplotlab/学习教程/3d_test.py
Normal file
19
Python/matplotlab/学习教程/3d_test.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
|
||||
# 生成数据
|
||||
|
||||
x = np.arange(-4,4,0.25)
|
||||
y = np.arange(-4,4,0.25)
|
||||
X,Y = np.meshgrid(x,y)
|
||||
R = np.sqrt(X**2+Y**2)
|
||||
Z = np.sin(R)
|
||||
|
||||
# 画图
|
||||
|
||||
fig = plt.figure()
|
||||
ax = Axes3D(fig)
|
||||
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap = plt.get_cmap('rainbow'))
|
||||
ax.contourf(X, Y, Z, zdir='x', offset=-4, cmap=plt.get_cmap('rainbow'))
|
||||
plt.show()
|
||||
26
Python/matplotlab/学习教程/animation_test.py
Normal file
26
Python/matplotlab/学习教程/animation_test.py
Normal file
@@ -0,0 +1,26 @@
|
||||
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,
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
line, = ax.plot(x, np.sin(x))
|
||||
|
||||
ani = animation.FuncAnimation(fig=fig,
|
||||
func=animate,
|
||||
frames=100,
|
||||
init_func=init,
|
||||
interval=20,
|
||||
blit=True)
|
||||
plt.show()
|
||||
@@ -29,5 +29,11 @@ plt.yticks([-2,-1.8,-1,1.22,3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good
|
||||
ax = plt.gca()
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
# 调整刻度及边框位置
|
||||
ax.xaxis.set_ticks_position('top')
|
||||
ax.spines['bottom'].set_position(('data',10))
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
ax.spines['left'].set_position(('data',0))
|
||||
# 展示图像
|
||||
plt.show()
|
||||
45
Python/matplotlab/学习教程/legend_test.py
Normal file
45
Python/matplotlab/学习教程/legend_test.py
Normal file
@@ -0,0 +1,45 @@
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
x = np.linspace(-3,3,50)
|
||||
y1 = 2*x+1
|
||||
y2 = x**2
|
||||
|
||||
plt.figure()
|
||||
|
||||
# 坐标轴范围
|
||||
plt.xlim((-4,5))
|
||||
plt.ylim((-2,10))
|
||||
|
||||
# 坐标
|
||||
ticks = np.linspace(-1,2,5)
|
||||
plt.xticks(ticks)
|
||||
|
||||
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
|
||||
|
||||
# 线条
|
||||
plt.plot(x,y1,label='linear line')
|
||||
plt.plot(x,y2,label='quick line',color='red',linewidth=1,linestyle='--')
|
||||
|
||||
# 图例
|
||||
plt.legend(loc='upper right')
|
||||
|
||||
# 设置x轴位置
|
||||
ax = plt.gca()
|
||||
ax.spines['bottom'].set_position(('data', 0))
|
||||
|
||||
# 标注
|
||||
|
||||
x0 = 1
|
||||
y0 = 2*x0 + 1
|
||||
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
|
||||
plt.scatter([x0, ], [y0, ], s=50, color='b')
|
||||
|
||||
|
||||
# 注释annotate
|
||||
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"))
|
||||
|
||||
# 注释 text
|
||||
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',fontdict={'size': 16, 'color': 'r'})
|
||||
# 展示
|
||||
plt.show()
|
||||
0
Python/matplotlab/学习教程/subplot_test.py
Normal file
0
Python/matplotlab/学习教程/subplot_test.py
Normal file
60
Python/matplotlab/学习教程/type_test.py
Normal file
60
Python/matplotlab/学习教程/type_test.py
Normal file
@@ -0,0 +1,60 @@
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
# 生成数据
|
||||
x = np.random.normal(0,1,1024)
|
||||
y = np.random.normal(0,1,1024)
|
||||
t = np.arctan2(x,y)
|
||||
|
||||
# 绘制散点图
|
||||
plt.subplot(2,2,1)
|
||||
plt.scatter(x,y,s = 75,c = t,alpha=0.5)
|
||||
|
||||
# 生成数据
|
||||
X = np.arange(12)
|
||||
Y1 = (1 - X / float(12)) * np.random.uniform(0.5, 1.0, 12)
|
||||
Y2 = (1 - X / float(12)) * np.random.uniform(0.5, 1.0, 12)
|
||||
|
||||
# 绘制柱状图
|
||||
plt.subplot(2,2,2)
|
||||
plt.bar(X, +Y1, facecolor='#FFCCCC', edgecolor='white')
|
||||
plt.bar(X, -Y2, facecolor='#6699CC', edgecolor='white')
|
||||
|
||||
# zip()函数将两个可迭代对象打包成可迭代元组。
|
||||
for x, y in zip(X, Y1):
|
||||
# ha: horizontal alignment
|
||||
# va: vertical alignment
|
||||
plt.text(x, y , '%.2f' % y, ha='center', va='bottom')
|
||||
|
||||
for x, y in zip(X, Y2):
|
||||
# ha: horizontal alignment
|
||||
# va: vertical alignment
|
||||
plt.text(x, -y , '%.2f' % y, ha='center', va='top')
|
||||
|
||||
# 生成数据
|
||||
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)
|
||||
# meshgrid,由x,y打包成矩阵
|
||||
X,Y = np.meshgrid(x, y)
|
||||
# 绘制等高线地图
|
||||
plt.subplot(2,2,3)
|
||||
plt.contourf(X, Y, f(X, Y),10, alpha=.75, cmap=plt.cm.RdBu)
|
||||
c = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
|
||||
plt.clabel(c, inline=True, fontsize=10)
|
||||
|
||||
# 生成数据
|
||||
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.subplot(2,2,4)
|
||||
plt.imshow(a, interpolation='nearest', cmap='RdBu', origin='lower')
|
||||
plt.colorbar(shrink=.92)
|
||||
|
||||
# 展示
|
||||
plt.show()
|
||||
Reference in New Issue
Block a user