matplotlib & pandas

This commit is contained in:
estomm
2020-09-26 22:03:11 +08:00
parent 73cc328c81
commit d31be4f219
599 changed files with 99925 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
# 图像的仿射变换
将仿射变换(Affine2D)预先添加到图像的数据变换允许操纵图像的形状和方向。这是变换链的概念的一个例子。
对于支持具有可选仿射变换的draw_image的后端(例如,agg,ps后端),输出的图像应该使其边界与虚线黄色矩形匹配。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
def get_image():
delta = 0.25
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2)
return Z
def do_plot(ax, Z, transform):
im = ax.imshow(Z, interpolation='none',
origin='lower',
extent=[-2, 4, -3, 2], clip_on=True)
trans_data = transform + ax.transData
im.set_transform(trans_data)
# display intended extent of the image
x1, x2, y1, y2 = im.get_extent()
ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "y--",
transform=trans_data)
ax.set_xlim(-5, 5)
ax.set_ylim(-4, 4)
# prepare image and figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
Z = get_image()
# image rotation
do_plot(ax1, Z, mtransforms.Affine2D().rotate_deg(30))
# image skew
do_plot(ax2, Z, mtransforms.Affine2D().skew_deg(30, 15))
# scale and reflection
do_plot(ax3, Z, mtransforms.Affine2D().scale(-1, .5))
# everything and a translation
do_plot(ax4, Z, mtransforms.Affine2D().
rotate_deg(30).skew_deg(30, 15).scale(-1, .5).translate(.5, -1))
plt.show()
```
![图像的仿射变换图示](https://matplotlib.org/_images/sphx_glr_affine_image_001.png)
## 参考
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.transforms.Affine2D
```
## 下载这个示例
- [下载python源码: affine_image.py](https://matplotlib.org/_downloads/affine_image.py)
- [下载Jupyter notebook: affine_image.ipynb](https://matplotlib.org/_downloads/affine_image.ipynb)

View File

@@ -0,0 +1,71 @@
# 倒勾图示例
倒勾图的示例:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
U, V = 12 * X, 12 * Y
data = [(-1.5, .5, -6, -6),
(1, -1, -46, 46),
(-3, -1, 11, -11),
(1, 1.5, 80, 80),
(0.5, 0.25, 25, 15),
(-1.5, -0.5, -5, 40)]
data = np.array(data, dtype=[('x', np.float32), ('y', np.float32),
('u', np.float32), ('v', np.float32)])
fig1, axs1 = plt.subplots(nrows=2, ncols=2)
# Default parameters, uniform grid
axs1[0, 0].barbs(X, Y, U, V)
# Arbitrary set of vectors, make them longer and change the pivot point
# (point around which they're rotated) to be the middle
axs1[0, 1].barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
# Showing colormapping with uniform grid. Fill the circle for an empty barb,
# don't round the values, and change some of the size parameters
axs1[1, 0].barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
# Change colors as well as the increments for parts of the barbs
axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
barbcolor=['b', 'g'], flip_barb=True,
barb_increments=dict(half=10, full=20, flag=100))
# Masked arrays are also supported
masked_u = np.ma.masked_array(data['u'])
masked_u[4] = 1000 # Bad value that should not be plotted when masked
masked_u[4] = np.ma.masked
# Identical plot to panel 2 in the first figure, but with the point at
# (0.5, 0.25) missing (masked)
fig2, ax2 = plt.subplots()
ax2.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle')
plt.show()
```
![倒勾图示例](https://matplotlib.org/_images/sphx_glr_barb_demo_001.png)
![倒勾图示例2](https://matplotlib.org/_images/sphx_glr_barb_demo_002.png)
## 参考
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.barbs
matplotlib.pyplot.barbs
```
## 下载这个示例
- [下载python源码: barb_demo.py](https://matplotlib.org/_downloads/barb_demo.py)
- [下载Jupyter notebook: barb_demo.ipynb](https://matplotlib.org/_downloads/barb_demo.ipynb)

View File

@@ -0,0 +1,48 @@
# 条形码示例
该演示展示了如何生成一维图像或“条形码”。
```python
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# the bar
x = np.where(np.random.rand(500) > 0.7, 1.0, 0.0)
axprops = dict(xticks=[], yticks=[])
barprops = dict(aspect='auto', cmap=plt.cm.binary, interpolation='nearest')
fig = plt.figure()
# a vertical barcode
ax1 = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops)
ax1.imshow(x.reshape((-1, 1)), **barprops)
# a horizontal barcode
ax2 = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops)
ax2.imshow(x.reshape((1, -1)), **barprops)
plt.show()
```
![条形码示例](https://matplotlib.org/_images/sphx_glr_barcode_demo_001.png)
## 参考
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
```
## 下载这个示例
- [下载python源码: barcode_demo.py](https://matplotlib.org/_downloads/barcode_demo.py)
- [下载Jupyter notebook: barcode_demo.ipynb](https://matplotlib.org/_downloads/barcode_demo.ipynb)

View File

@@ -0,0 +1,55 @@
# 等高线角遮盖
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib.pyplot as plt
import numpy as np
# Data to plot.
x, y = np.meshgrid(np.arange(7), np.arange(10))
z = np.sin(0.5 * x) * np.cos(0.52 * y)
# Mask various z values.
mask = np.zeros_like(z, dtype=bool)
mask[2, 3:5] = True
mask[3:5, 4] = True
mask[7, 2] = True
mask[5, 0] = True
mask[0, 6] = True
z = np.ma.array(z, mask=mask)
corner_masks = [False, True]
fig, axs = plt.subplots(ncols=2)
for ax, corner_mask in zip(axs, corner_masks):
cs = ax.contourf(x, y, z, corner_mask=corner_mask)
ax.contour(cs, colors='k')
ax.set_title('corner_mask = {0}'.format(corner_mask))
# Plot grid.
ax.grid(c='k', ls='-', alpha=0.3)
# Indicate masked points with red circles.
ax.plot(np.ma.array(x, mask=~mask), y, 'ro')
plt.show()
```
![条形码示例](https://matplotlib.org/_images/sphx_glr_contour_corner_mask_001.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
```
## 下载这个示例
- [下载python源码: contour_corner_mask.py](https://matplotlib.org/_downloads/contour_corner_mask.py)
- [下载Jupyter notebook: contour_corner_mask.ipynb](https://matplotlib.org/_downloads/contour_corner_mask.ipynb)

View File

@@ -0,0 +1,143 @@
# 等高线演示
演示简单的等高线绘制,图像上的等高线带有等高线的颜色条,并标出等高线。
另见[轮廓图像示例](https://matplotlib.org/gallery/images_contours_and_fields/contour_image.html)。
```python
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
```
使用默认颜色创建带有标签的简单等高线图。clabel的内联参数将控制标签是否画在轮廓的线段上,移除标签下面的线。
```python
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
ax.clabel(CS, inline=1, fontsize=10)
ax.set_title('Simplest default with labels')
```
![等高线演示示例](https://matplotlib.org/_images/sphx_glr_contour_demo_001.png)
等高线的标签可以手动放置,通过提供位置列表(在数据坐标中)。有关交互式布局,请参见ginput_book_clabel.py。
```python
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)]
ax.clabel(CS, inline=1, fontsize=10, manual=manual_locations)
ax.set_title('labels at selected locations')
```
![等高线演示示例2](https://matplotlib.org/_images/sphx_glr_contour_demo_002.png)
你可以强制所有的等高线是相同的颜色。
```python
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6,
colors='k', # negative contours will be dashed by default
)
ax.clabel(CS, fontsize=9, inline=1)
ax.set_title('Single color - negative contours dashed')
```
![等高线演示示例3](https://matplotlib.org/_images/sphx_glr_contour_demo_003.png)
你可以将负轮廓设置为实线而不是虚线:
```python
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6,
colors='k', # negative contours will be dashed by default
)
ax.clabel(CS, fontsize=9, inline=1)
ax.set_title('Single color - negative contours solid')
```
![等高线演示示例4](https://matplotlib.org/_images/sphx_glr_contour_demo_004.png)
并且你可以手动指定轮廓的颜色。
```python
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6,
linewidths=np.arange(.5, 4, .5),
colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5')
)
ax.clabel(CS, fontsize=9, inline=1)
ax.set_title('Crazy lines')
```
![等高线演示示例5](https://matplotlib.org/_images/sphx_glr_contour_demo_005.png)
也可以使用颜色图来指定颜色;默认的颜色图将用于等高线。
```python
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
cmap=cm.gray, extent=(-3, 3, -2, 2))
levels = np.arange(-1.2, 1.6, 0.2)
CS = ax.contour(Z, levels, origin='lower', cmap='flag',
linewidths=2, extent=(-3, 3, -2, 2))
# Thicken the zero contour.
zc = CS.collections[6]
plt.setp(zc, linewidth=4)
ax.clabel(CS, levels[1::2], # label every second level
inline=1, fmt='%1.1f', fontsize=14)
# make a colorbar for the contour lines
CB = fig.colorbar(CS, shrink=0.8, extend='both')
ax.set_title('Lines with colorbar')
# We can still add a colorbar for the image, too.
CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8)
# This makes the original colorbar look a bit out of place,
# so let's improve its position.
l, b, w, h = ax.get_position().bounds
ll, bb, ww, hh = CB.ax.get_position().bounds
CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])
plt.show()
```
![等高线演示示例6](https://matplotlib.org/_images/sphx_glr_contour_demo_006.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.axes.Axes.clabel
matplotlib.pyplot.clabel
matplotlib.axes.Axes.set_position
matplotlib.axes.Axes.get_position
```
## 下载这个示例
- [下载python源码: contour_demo.py](https://matplotlib.org/_downloads/contour_demo.py)
- [下载Jupyter notebook: contour_demo.ipynb](https://matplotlib.org/_downloads/contour_demo.ipynb)

View File

@@ -0,0 +1,110 @@
# 等高线图像
等高线,填充等高线和图像绘制的测试组合。 有关等高线标记,另请参见等高线演示示例。
本演示的重点是展示如何在图像上正确展示等高线,以及如何使两者按照需要定向。 特别要注意 [“origin”和“extent”](https://matplotlib.org/tutorials/intermediate/imshow_extent.html) 关键字参数在imshow和contour中的用法。
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
# Default delta is large because that makes it fast, and it illustrates
# the correct registration between image and contours.
delta = 0.5
extent = (-3, 4, -4, 3)
x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
# Boost the upper limit to avoid truncation errors.
levels = np.arange(-2.0, 1.601, 0.4)
norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn
fig, _axs = plt.subplots(nrows=2, ncols=2)
fig.subplots_adjust(hspace=0.3)
axs = _axs.flatten()
cset1 = axs[0].contourf(X, Y, Z, levels, norm=norm,
cmap=cm.get_cmap(cmap, len(levels) - 1))
# It is not necessary, but for the colormap, we need only the
# number of levels minus 1. To avoid discretization error, use
# either this number or a large number such as the default (256).
# If we want lines as well as filled regions, we need to call
# contour separately; don't try to change the edgecolor or edgewidth
# of the polygons in the collections returned by contourf.
# Use levels output from previous call to guarantee they are the same.
cset2 = axs[0].contour(X, Y, Z, cset1.levels, colors='k')
# We don't really need dashed contour lines to indicate negative
# regions, so let's turn them off.
for c in cset2.collections:
c.set_linestyle('solid')
# It is easier here to make a separate call to contour than
# to set up an array of colors and linewidths.
# We are making a thick green line as a zero contour.
# Specify the zero level as a tuple with only 0 in it.
cset3 = axs[0].contour(X, Y, Z, (0,), colors='g', linewidths=2)
axs[0].set_title('Filled contours')
fig.colorbar(cset1, ax=axs[0])
axs[1].imshow(Z, extent=extent, cmap=cmap, norm=norm)
axs[1].contour(Z, levels, colors='k', origin='upper', extent=extent)
axs[1].set_title("Image, origin 'upper'")
axs[2].imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm)
axs[2].contour(Z, levels, colors='k', origin='lower', extent=extent)
axs[2].set_title("Image, origin 'lower'")
# We will use the interpolation "nearest" here to show the actual
# image pixels.
# Note that the contour lines don't extend to the edge of the box.
# This is intentional. The Z values are defined at the center of each
# image pixel (each color block on the following subplot), so the
# domain that is contoured does not extend beyond these pixel centers.
im = axs[3].imshow(Z, interpolation='nearest', extent=extent,
cmap=cmap, norm=norm)
axs[3].contour(Z, levels, colors='k', origin='image', extent=extent)
ylim = axs[3].get_ylim()
axs[3].set_ylim(ylim[::-1])
axs[3].set_title("Origin from rc, reversed y-axis")
fig.colorbar(im, ax=axs[3])
fig.tight_layout()
plt.show()
```
![等高线图像示例](https://matplotlib.org/_images/sphx_glr_contour_image_001.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.colors.Normalize
```
## 下载这个示例
- [下载python源码: contour_image.py](https://matplotlib.org/_downloads/contour_image.py)
- [下载Jupyter notebook: contour_image.ipynb](https://matplotlib.org/_downloads/contour_image.ipynb)

View File

@@ -0,0 +1,111 @@
# 等高线标签演示
说明一些可以用等高线的标签做的更高级的东西。
另请参见[轮廓演示示例](https://matplotlib.org/gallery/images_contours_and_fields/contour_demo.html)。
```python
import matplotlib
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
```
定义我们的外观
```python
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
```
使用创造性的浮动类制作等高线的标签,遵循曼纽尔·梅茨的建议。
```python
# Define a class that forces representation of float to look a certain way
# This remove trailing zero so '1.0' becomes '1'
class nf(float):
def __repr__(self):
str = '%.1f' % (self.__float__(),)
if str[-1] == '0':
return '%.0f' % self.__float__()
else:
return '%.1f' % self.__float__()
# Basic contour plot
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
# Recast levels to new class
CS.levels = [nf(val) for val in CS.levels]
# Label levels with specially formatted floats
if plt.rcParams["text.usetex"]:
fmt = r'%r \%%'
else:
fmt = '%r %%'
ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)
```
![等高线标签演示示例](https://matplotlib.org/_images/sphx_glr_contour_label_demo_001.png)
使用字典用任意字符串标记等高线
```python
fig1, ax1 = plt.subplots()
# Basic contour plot
CS1 = ax1.contour(X, Y, Z)
fmt = {}
strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
for l, s in zip(CS1.levels, strs):
fmt[l] = s
# Label every other level using strings
ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10)
```
![等高线标签演示示例2](https://matplotlib.org/_images/sphx_glr_contour_label_demo_002.png)
使用Formatter来格式化
```python
fig2, ax2 = plt.subplots()
CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator())
fmt = ticker.LogFormatterMathtext()
fmt.create_dummy_axis()
ax2.clabel(CS2, CS2.levels, fmt=fmt)
ax2.set_title("$100^Z$")
plt.show()
```
![等高线标签演示示例3](https://matplotlib.org/_images/sphx_glr_contour_label_demo_003.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.axes.Axes.clabel
matplotlib.pyplot.clabel
matplotlib.ticker.LogFormatterMathtext
matplotlib.ticker.TickHelper.create_dummy_axis
```
## 下载这个示例
- [下载python源码: contour_image.py](https://matplotlib.org/_downloads/contour_image.py)
- [下载Jupyter notebook: contour_image.ipynb](https://matplotlib.org/_downloads/contour_image.ipynb)

View File

@@ -0,0 +1,136 @@
# Contourf演示
如何使用 [axes.Axes.contourf()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html#matplotlib.axes.Axes.contourf) 方法创建填充的等高线图。
```python
import numpy as np
import matplotlib.pyplot as plt
origin = 'lower'
delta = 0.025
x = y = np.arange(-3.0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
nr, nc = Z.shape
# put NaNs in one corner:
Z[-nr // 6:, -nc // 6:] = np.nan
# contourf will convert these to masked
Z = np.ma.array(Z)
# mask another corner:
Z[:nr // 6, :nc // 6] = np.ma.masked
# mask a circle in the middle:
interior = np.sqrt((X**2) + (Y**2)) < 0.5
Z[interior] = np.ma.masked
# We are using automatic selection of contour levels;
# this is usually not such a good idea, because they don't
# occur on nice boundaries, but we do it here for purposes
# of illustration.
fig1, ax2 = plt.subplots(constrained_layout=True)
CS = ax2.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin)
# Note that in the following, we explicitly pass in a subset of
# the contour levels used for the filled contours. Alternatively,
# We could pass in additional levels to provide extra resolution,
# or leave out the levels kwarg to use all of the original levels.
CS2 = ax2.contour(CS, levels=CS.levels[::2], colors='r', origin=origin)
ax2.set_title('Nonsense (3 masked regions)')
ax2.set_xlabel('word length anomaly')
ax2.set_ylabel('sentence length anomaly')
# Make a colorbar for the ContourSet returned by the contourf call.
cbar = fig1.colorbar(CS)
cbar.ax.set_ylabel('verbosity coefficient')
# Add the contour line levels to the colorbar
cbar.add_lines(CS2)
fig2, ax2 = plt.subplots(constrained_layout=True)
# Now make a contour plot with the levels specified,
# and with the colormap generated automatically from a list
# of colors.
levels = [-1.5, -1, -0.5, 0, 0.5, 1]
CS3 = ax2.contourf(X, Y, Z, levels,
colors=('r', 'g', 'b'),
origin=origin,
extend='both')
# Our data range extends outside the range of levels; make
# data below the lowest contour level yellow, and above the
# highest level cyan:
CS3.cmap.set_under('yellow')
CS3.cmap.set_over('cyan')
CS4 = ax2.contour(X, Y, Z, levels,
colors=('k',),
linewidths=(3,),
origin=origin)
ax2.set_title('Listed colors (3 masked regions)')
ax2.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14)
# Notice that the colorbar command gets all the information it
# needs from the ContourSet object, CS3.
fig2.colorbar(CS3)
# Illustrate all 4 possible "extend" settings:
extends = ["neither", "both", "min", "max"]
cmap = plt.cm.get_cmap("winter")
cmap.set_under("magenta")
cmap.set_over("yellow")
# Note: contouring simply excludes masked or nan regions, so
# instead of using the "bad" colormap value for them, it draws
# nothing at all in them. Therefore the following would have
# no effect:
# cmap.set_bad("red")
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax, extend in zip(axs.ravel(), extends):
cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin)
fig.colorbar(cs, ax=ax, shrink=0.9)
ax.set_title("extend = %s" % extend)
ax.locator_params(nbins=4)
plt.show()
```
![Contourf演示](https://matplotlib.org/_images/sphx_glr_contourf_demo_001.png)
![Contourf演示2](https://matplotlib.org/_images/sphx_glr_contourf_demo_002.png)
![Contourf演示3](https://matplotlib.org/_images/sphx_glr_contourf_demo_003.png)
## 参考
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
matplotlib.axes.Axes.clabel
matplotlib.pyplot.clabel
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.colors.Colormap
matplotlib.colors.Colormap.set_bad
matplotlib.colors.Colormap.set_under
matplotlib.colors.Colormap.set_over
```
## 下载这个示例
- [下载python源码: contourf_demo.py](https://matplotlib.org/_downloads/contourf_demo.py)
- [下载Jupyter notebook: contourf_demo.ipynb](https://matplotlib.org/_downloads/contourf_demo.ipynb)

View File

@@ -0,0 +1,69 @@
# Contourf 影线法
演示填充轮廓图形与阴影模式。
```python
import matplotlib.pyplot as plt
import numpy as np
# invent some numbers, turning the x and y arrays into simple
# 2d arrays, which make combining them together easier.
x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)
# we no longer need x and y to be 2 dimensional, so flatten them.
x, y = x.flatten(), y.flatten()
```
图1:最简单的带彩色条的阴影图
```python
fig1, ax1 = plt.subplots()
cs = ax1.contourf(x, y, z, hatches=['-', '/', '\\', '//'],
cmap='gray', extend='both', alpha=0.5)
fig1.colorbar(cs)
```
![Contourf 影线法](https://matplotlib.org/_images/sphx_glr_contourf_hatching_001.png)
绘制2:没有带图例的颜色的阴影图
```python
fig2, ax2 = plt.subplots()
n_levels = 6
ax2.contour(x, y, z, n_levels, colors='black', linestyles='-')
cs = ax2.contourf(x, y, z, n_levels, colors='none',
hatches=['.', '/', '\\', None, '\\\\', '*'],
extend='lower')
# create a legend for the contour set
artists, labels = cs.legend_elements()
ax2.legend(artists, labels, handleheight=2)
plt.show()
```
![Contourf 影线法2](https://matplotlib.org/_images/sphx_glr_contourf_hatching_002.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.axes.Axes.legend
matplotlib.pyplot.legend
matplotlib.contour.ContourSet
matplotlib.contour.ContourSet.legend_elements
```
## 下载这个示例
- [下载python源码: contourf_hatching.py](https://matplotlib.org/_downloads/contourf_hatching.py)
- [下载Jupyter notebook: contourf_hatching.ipynb](https://matplotlib.org/_downloads/contourf_hatching.ipynb)

View File

@@ -0,0 +1,69 @@
# Contourf 与记录颜色刻度
演示在 Contourf 中记录颜色的标度
```python
import matplotlib.pyplot as plt
import numpy as np
from numpy import ma
from matplotlib import ticker, cm
N = 100
x = np.linspace(-3.0, 3.0, N)
y = np.linspace(-2.0, 2.0, N)
X, Y = np.meshgrid(x, y)
# A low hump with a spike coming out.
# Needs to have z/colour axis on a log scale so we see both hump and spike.
# linear scale only shows the spike.
Z1 = np.exp(-(X)**2 - (Y)**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
z = Z1 + 50 * Z2
# Put in some negative values (lower left corner) to cause trouble with logs:
z[:5, :5] = -1
# The following is not strictly essential, but it will eliminate
# a warning. Comment it out to see the warning.
z = ma.masked_where(z <= 0, z)
# Automatic selection of levels works; setting the
# log locator tells contourf to use a log scale:
fig, ax = plt.subplots()
cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)
# Alternatively, you can manually set the levels
# and the norm:
# lev_exp = np.arange(np.floor(np.log10(z.min())-1),
# np.ceil(np.log10(z.max())+1))
# levs = np.power(10, lev_exp)
# cs = ax.contourf(X, Y, z, levs, norm=colors.LogNorm())
cbar = fig.colorbar(cs)
plt.show()
```
![Contourf 与记录颜色刻度示例](https://matplotlib.org/_images/sphx_glr_contourf_log_001.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.axes.Axes.legend
matplotlib.pyplot.legend
matplotlib.ticker.LogLocator
```
## 下载这个示例
- [下载python源码: contourf_log.py](https://matplotlib.org/_downloads/contourf_log.py)
- [下载Jupyter notebook: contourf_log.ipynb](https://matplotlib.org/_downloads/contourf_log.ipynb)

View File

@@ -0,0 +1,2 @@
# 从颜色列表创建颜色图

View File

@@ -0,0 +1,86 @@
# BboxImage 演示
BboxImage可用于根据边界框定位图像。此演示演示如何在text.Text的边界框内显示图像以及如何手动为图像创建边界框。
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox
fig, (ax1, ax2) = plt.subplots(ncols=2)
# ----------------------------
# Create a BboxImage with Text
# ----------------------------
txt = ax1.text(0.5, 0.5, "test", size=30, ha="center", color="w")
kwargs = dict()
bbox_image = BboxImage(txt.get_window_extent,
norm=None,
origin=None,
clip_on=False,
**kwargs
)
a = np.arange(256).reshape(1, 256)/256.
bbox_image.set_data(a)
ax1.add_artist(bbox_image)
# ------------------------------------
# Create a BboxImage for each colormap
# ------------------------------------
a = np.linspace(0, 1, 256).reshape(1, -1)
a = np.vstack((a, a))
# List of all colormaps; skip reversed colormaps.
maps = sorted(m for m in plt.cm.cmap_d if not m.endswith("_r"))
ncol = 2
nrow = len(maps)//ncol + 1
xpad_fraction = 0.3
dx = 1./(ncol + xpad_fraction*(ncol - 1))
ypad_fraction = 0.3
dy = 1./(nrow + ypad_fraction*(nrow - 1))
for i, m in enumerate(maps):
ix, iy = divmod(i, nrow)
bbox0 = Bbox.from_bounds(ix*dx*(1 + xpad_fraction),
1. - iy*dy*(1 + ypad_fraction) - dy,
dx, dy)
bbox = TransformedBbox(bbox0, ax2.transAxes)
bbox_image = BboxImage(bbox,
cmap=plt.get_cmap(m),
norm=None,
origin=None,
**kwargs
)
bbox_image.set_data(a)
ax2.add_artist(bbox_image)
plt.show()
```
![BboxImage 演示](https://matplotlib.org/_images/sphx_glr_demo_bboximage_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.image.BboxImage
matplotlib.transforms.Bbox
matplotlib.transforms.TransformedBbox
matplotlib.text.Text
```
## 下载这个示例
- [下载python源码: demo_bboximage.py](https://matplotlib.org/_downloads/demo_bboximage.py)
- [下载Jupyter notebook: demo_bboximage.ipynb](https://matplotlib.org/_downloads/demo_bboximage.ipynb)

View File

@@ -0,0 +1,36 @@
# Figimage 演示
这说明了在没有轴对象的情况下,直接将图像放置在图形中。
```python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
Z = np.arange(10000).reshape((100, 100))
Z[:, 50:] = 1
im1 = fig.figimage(Z, xo=50, yo=0, origin='lower')
im2 = fig.figimage(Z, xo=100, yo=100, alpha=.8, origin='lower')
plt.show()
```
![Figimage 演示](https://matplotlib.org/_images/sphx_glr_figimage_demo_001.png)
## 参考
本例中显示了下列函数、方法、类和模块的使用:
```python
matplotlib.figure.Figure
matplotlib.figure.Figure.figimage
matplotlib.pyplot.figimage
```
## 下载这个示例
- [下载python源码: figimage_demo.py](https://matplotlib.org/_downloads/figimage_demo.py)
- [下载Jupyter notebook: figimage_demo.ipynb](https://matplotlib.org/_downloads/figimage_demo.ipynb)

View File

@@ -0,0 +1,275 @@
# 创建带注释的热度图
通常希望将依赖于两个独立变量的数据显示为彩色编码图像图。这通常被称为热度图。如果数据是分类的,则称为分类热度图。Matplotlib的[imshow](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow)功能使得这种图的制作特别容易。
以下示例显示如何使用注释创建热图 我们将从一个简单的示例开始,并将其扩展为可用作通用功能。
## 一种简单的分类热度图
我们可以从定义一些数据开始。我们需要的是一个二维列表或数组,它定义了颜色代码的数据。然后,我们还需要类别的两个列表或数组;当然,这些列表中的元素数量需要沿着各自的轴匹配数据。热度图本身是一个 [imshow](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow) 图,其标签设置为我们所拥有的类别。请注意,重要的是同时设置刻度位置([Set_Xticks](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xticks.html#matplotlib.axes.Axes.set_xticks))和刻度标签([set_xtick标签](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html#matplotlib.axes.Axes.set_xticklabels)),否则它们将变得不同步。位置只是升序整数,而节拍标签则是要显示的标签。最后,我们可以通过在每个单元格内创建一个[文本](https://matplotlib.org/api/text_api.html#matplotlib.text.Text)来标记数据本身,以显示该单元格的值。
```python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# sphinx_gallery_thumbnail_number = 2
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
fig, ax = plt.subplots()
im = ax.imshow(harvest)
# We want to show all ticks...
ax.set_xticks(np.arange(len(farmers)))
ax.set_yticks(np.arange(len(vegetables)))
# ... and label them with the respective list entries
ax.set_xticklabels(farmers)
ax.set_yticklabels(vegetables)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = ax.text(j, i, harvest[i, j],
ha="center", va="center", color="w")
ax.set_title("Harvest of local farmers (in tons/year)")
fig.tight_layout()
plt.show()
```
![热度图示例](https://matplotlib.org/_images/sphx_glr_image_annotated_heatmap_001.png)
## 使用辅助函数的编码风格
正如在[编码风格](https://matplotlib.org/tutorials/introductory/usage.html#coding-styles)中所讨论的,人们可能希望重用这样的代码,为不同的输入数据和/或不同的轴创建某种热映射。我们创建了一个函数,该函数接受数据以及行和列标签作为输入,并允许用于自定义绘图的参数。
在这里,除了上面的内容之外,我们还想创建一个颜色条,并将标签放在热图的上面而不是下面。注释应根据阈值获得不同的颜色,以便与像素颜色形成更好的对比度。最后,我们关闭周围的轴刺,创建一个白线网格来分隔细胞。
```python
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Arguments:
data : A 2D numpy array of shape (N,M)
row_labels : A list or array of length N with the labels
for the rows
col_labels : A list or array of length M with the labels
for the columns
Optional arguments:
ax : A matplotlib.axes.Axes instance to which the heatmap
is plotted. If not provided, use current axes or
create a new one.
cbar_kw : A dictionary with arguments to
:meth:`matplotlib.Figure.colorbar`.
cbarlabel : The label for the colorbar
All other arguments are directly passed on to the imshow call.
"""
if not ax:
ax = plt.gca()
# Plot the heatmap
im = ax.imshow(data, **kwargs)
# Create colorbar
cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
# We want to show all ticks...
ax.set_xticks(np.arange(data.shape[1]))
ax.set_yticks(np.arange(data.shape[0]))
# ... and label them with the respective list entries.
ax.set_xticklabels(col_labels)
ax.set_yticklabels(row_labels)
# Let the horizontal axes labeling appear on top.
ax.tick_params(top=True, bottom=False,
labeltop=True, labelbottom=False)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
rotation_mode="anchor")
# Turn spines off and create white grid.
for edge, spine in ax.spines.items():
spine.set_visible(False)
ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
ax.tick_params(which="minor", bottom=False, left=False)
return im, cbar
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["black", "white"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Arguments:
im : The AxesImage to be labeled.
Optional arguments:
data : Data used to annotate. If None, the image's data is used.
valfmt : The format of the annotations inside the heatmap.
This should either use the string format method, e.g.
"$ {x:.2f}", or be a :class:`matplotlib.ticker.Formatter`.
textcolors : A list or array of two color specifications. The first is
used for values below a threshold, the second for those
above.
threshold : Value in data units according to which the colors from
textcolors are applied. If None (the default) uses the
middle of the colormap as separation.
Further arguments are passed on to the created text labels.
"""
if not isinstance(data, (list, np.ndarray)):
data = im.get_array()
# Normalize the threshold to the images color range.
if threshold is not None:
threshold = im.norm(threshold)
else:
threshold = im.norm(data.max())/2.
# Set default alignment to center, but allow it to be
# overwritten by textkw.
kw = dict(horizontalalignment="center",
verticalalignment="center")
kw.update(textkw)
# Get the formatter in case a string is supplied
if isinstance(valfmt, str):
valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)
# Loop over the data and create a `Text` for each "pixel".
# Change the text's color depending on the data.
texts = []
for i in range(data.shape[0]):
for j in range(data.shape[1]):
kw.update(color=textcolors[im.norm(data[i, j]) > threshold])
text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
texts.append(text)
return texts
```
以上所述使我们能够保持实际的绘制创作非常紧凑。
```python
fig, ax = plt.subplots()
im, cbar = heatmap(harvest, vegetables, farmers, ax=ax,
cmap="YlGn", cbarlabel="harvest [t/year]")
texts = annotate_heatmap(im, valfmt="{x:.1f} t")
fig.tight_layout()
plt.show()
```
![热度图示例2](https://matplotlib.org/_images/sphx_glr_image_annotated_heatmap_002.png)
## 一些更复杂的热度图示例
在下面的文章中,我们将通过在不同的情况下使用不同的参数来展示前面创建的函数的多样性。
```python
np.random.seed(19680801)
fig, ((ax, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6))
# Replicate the above example with a different font size and colormap.
im, _ = heatmap(harvest, vegetables, farmers, ax=ax,
cmap="Wistia", cbarlabel="harvest [t/year]")
annotate_heatmap(im, valfmt="{x:.1f}", size=7)
# Create some new data, give further arguments to imshow (vmin),
# use an integer format on the annotations and provide some colors.
data = np.random.randint(2, 100, size=(7, 7))
y = ["Book {}".format(i) for i in range(1, 8)]
x = ["Store {}".format(i) for i in list("ABCDEFG")]
im, _ = heatmap(data, y, x, ax=ax2, vmin=0,
cmap="magma_r", cbarlabel="weekly sold copies")
annotate_heatmap(im, valfmt="{x:d}", size=7, threshold=20,
textcolors=["red", "white"])
# Sometimes even the data itself is categorical. Here we use a
# :class:`matplotlib.colors.BoundaryNorm` to get the data into classes
# and use this to colorize the plot, but also to obtain the class
# labels from an array of classes.
data = np.random.randn(6, 6)
y = ["Prod. {}".format(i) for i in range(10, 70, 10)]
x = ["Cycle {}".format(i) for i in range(1, 7)]
qrates = np.array(list("ABCDEFG"))
norm = matplotlib.colors.BoundaryNorm(np.linspace(-3.5, 3.5, 8), 7)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: qrates[::-1][norm(x)])
im, _ = heatmap(data, y, x, ax=ax3,
cmap=plt.get_cmap("PiYG", 7), norm=norm,
cbar_kw=dict(ticks=np.arange(-3, 4), format=fmt),
cbarlabel="Quality Rating")
annotate_heatmap(im, valfmt=fmt, size=9, fontweight="bold", threshold=-1,
textcolors=["red", "black"])
# We can nicely plot a correlation matrix. Since this is bound by -1 and 1,
# we use those as vmin and vmax. We may also remove leading zeros and hide
# the diagonal elements (which are all 1) by using a
# :class:`matplotlib.ticker.FuncFormatter`.
corr_matrix = np.corrcoef(np.random.rand(6, 5))
im, _ = heatmap(corr_matrix, vegetables, vegetables, ax=ax4,
cmap="PuOr", vmin=-1, vmax=1,
cbarlabel="correlation coeff.")
def func(x, pos):
return "{:.2f}".format(x).replace("0.", ".").replace("1.00", "")
annotate_heatmap(im, valfmt=matplotlib.ticker.FuncFormatter(func), size=7)
plt.tight_layout()
plt.show()
```
![热度图示例3](https://matplotlib.org/_images/sphx_glr_image_annotated_heatmap_003.png)
## 参考
下面的示例显示了以下函数和方法的用法:
```python
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
```
## 下载这个示例
- [下载python源码: image_annotated_heatmap.py](https://matplotlib.org/_downloads/image_annotated_heatmap.py)
- [下载Jupyter notebook: image_annotated_heatmap.ipynb](https://matplotlib.org/_downloads/image_annotated_heatmap.ipynb)

View File

@@ -0,0 +1,39 @@
# 使用补丁剪切图像
演示的图像,已被一个圆形补丁裁剪。
```python
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cbook as cbook
with cbook.get_sample_data('grace_hopper.png') as image_file:
image = plt.imread(image_file)
fig, ax = plt.subplots()
im = ax.imshow(image)
patch = patches.Circle((260, 200), radius=200, transform=ax.transData)
im.set_clip_path(patch)
ax.axis('off')
plt.show()
```
![使用补丁剪切图像示例](https://matplotlib.org/_images/sphx_glr_image_clip_path_001.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.artist.Artist.set_clip_path
```
## 下载这个示例
- [下载python源码: image_clip_path.py](https://matplotlib.org/_downloads/image_clip_path.py)
- [下载Jupyter notebook: image_clip_path.ipynb](https://matplotlib.org/_downloads/image_clip_path.ipynb)

View File

@@ -0,0 +1,176 @@
# 图像演示
在Matplotlib中绘制图像的许多方法。
在Matplotlib中绘制图像最常见的方法是使用 [imShow()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow)。下面的示例演示了imShow的许多功能以及您可以创建的许多图像。
```python
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch
```
首先,我们将生成一个简单的二元正态分布。
```python
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
origin='lower', extent=[-3, 3, -3, 3],
vmax=abs(Z).max(), vmin=-abs(Z).max())
plt.show()
```
![图像演示示例](https://matplotlib.org/_images/sphx_glr_image_demo_001.png)
还可以显示图片的图像。
```python
# A sample image
with cbook.get_sample_data('ada.png') as image_file:
image = plt.imread(image_file)
fig, ax = plt.subplots()
ax.imshow(image)
ax.axis('off') # clear x-axis and y-axis
# And another image
w, h = 512, 512
with cbook.get_sample_data('ct.raw.gz', asfileobj=True) as datafile:
s = datafile.read()
A = np.fromstring(s, np.uint16).astype(float).reshape((w, h))
A /= A.max()
fig, ax = plt.subplots()
extent = (0, 25, 0, 25)
im = ax.imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent)
markers = [(15.9, 14.5), (16.8, 15)]
x, y = zip(*markers)
ax.plot(x, y, 'o')
ax.set_title('CT density')
plt.show()
```
![图像演示示例2](https://matplotlib.org/_images/sphx_glr_image_demo_002.png)
![图像演示示例3](https://matplotlib.org/_images/sphx_glr_image_demo_003.png)
## 插值图像
也可以在显示图像之前对其进行插值。请注意,因为这可能会影响数据的外观,但它有助于实现您想要的外观。下面我们将显示相同的(小)数组,使用三种不同的插值方法进行插值。
A[i, j]处的像素的中心绘制在 i + 0.5,i + 0.5 处。 如果使用interpolation ='nearest',则由(i,j) 和 (i + 1, j + 1) 限定的区域将具有相同的颜色。如果使用插值,像素中心的颜色与最近的颜色相同,但其他像素将在相邻像素之间进行插值。
早期版本的matplotlib(<0.63)试图通过设置视图限制来隐藏边缘效果,以便它们不可见。最近在antigrain中的一个误差修复,以及利用此修复的matplotlib._image模块中的一个新实现,不再需要它。为了防止边缘效应,在进行插值时,matplotlib._image模块现在用边缘周围相同的像素填充输入数组。 例如,如果你有一个5x5数组,颜色a-y如下:
```
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
```
_image模块创建填充数组:
```
a a b c d e e
a a b c d e e
f f g h i j j
k k l m n o o
p p q r s t t
o u v w x y y
o u v w x y y
```
进行插值/调整大小,然后提取中心区域。这允许你绘制没有边缘效果的阵列的整个范围,例如,使用不同的插值方法将多个不同大小的图像叠加在一起 - 请参阅[图层图像](https://matplotlib.org/gallery/images_contours_and_fields/layer_images.html)。它还意味着性能损失,因为必须创建这个新的临时填充数组。复杂的插值也意味着性能损失,因此如果您需要最大性能或具有非常大的图像,建议插值=“最近”。
```python
A = np.random.rand(5, 5)
fig, axs = plt.subplots(1, 3, figsize=(10, 3))
for ax, interp in zip(axs, ['nearest', 'bilinear', 'bicubic']):
ax.imshow(A, interpolation=interp)
ax.set_title(interp.capitalize())
ax.grid(True)
plt.show()
```
![图像演示示例4](https://matplotlib.org/_images/sphx_glr_image_demo_004.png)
可以使用“原点”参数指定图像应以数组原点 x[0, 0] 绘制在左上角还是右下角。您还可以在matplotLibrary c文件中控制默认设置Image.Source。有关此主题的更多信息,请参阅关于起源和范围的完整指南。
```python
x = np.arange(120).reshape((10, 12))
interp = 'bilinear'
fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5))
axs[0].set_title('blue should be up')
axs[0].imshow(x, origin='upper', interpolation=interp)
axs[1].set_title('blue should be down')
axs[1].imshow(x, origin='lower', interpolation=interp)
plt.show()
```
![图像演示示例5](https://matplotlib.org/_images/sphx_glr_image_demo_005.png)
最后,我们将使用剪辑路径显示图像。
```python
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]])
patch = PathPatch(path, facecolor='none')
fig, ax = plt.subplots()
ax.add_patch(patch)
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=[-3, 3, -3, 3],
clip_path=patch, clip_on=True)
im.set_clip_path(patch)
plt.show()
```
![图像演示示例6](https://matplotlib.org/_images/sphx_glr_image_demo_006.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.artist.Artist.set_clip_path
matplotlib.patches.PathPatch
```
## 下载这个示例
- [下载python源码: image_demo.py](https://matplotlib.org/_downloads/image_demo.py)
- [下载Jupyter notebook: image_demo.ipynb](https://matplotlib.org/_downloads/image_demo.ipynb)

View File

@@ -0,0 +1,94 @@
# 图像掩码
显示与掩码数组输入和范围以外的颜色。
第二个子图说明了如何使用边界规范来获得填充轮廓效果。
```python
from copy import copy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
# compute some interesting data
x0, x1 = -5, 5
y0, y1 = -3, 3
x = np.linspace(x0, x1, 500)
y = np.linspace(y0, y1, 500)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
# Set up a colormap:
# use copy so that we do not mutate the global colormap instance
palette = copy(plt.cm.gray)
palette.set_over('r', 1.0)
palette.set_under('g', 1.0)
palette.set_bad('b', 1.0)
# Alternatively, we could use
# palette.set_bad(alpha = 0.0)
# to make the bad region transparent. This is the default.
# If you comment out all the palette.set* lines, you will see
# all the defaults; under and over will be colored with the
# first and last colors in the palette, respectively.
Zm = np.ma.masked_where(Z > 1.2, Z)
# By setting vmin and vmax in the norm, we establish the
# range to which the regular palette color scale is applied.
# Anything above that range is colored based on palette.set_over, etc.
# set up the Axes objets
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(6, 5.4))
# plot using 'continuous' color map
im = ax1.imshow(Zm, interpolation='bilinear',
cmap=palette,
norm=colors.Normalize(vmin=-1.0, vmax=1.0),
aspect='auto',
origin='lower',
extent=[x0, x1, y0, y1])
ax1.set_title('Green=low, Red=high, Blue=masked')
cbar = fig.colorbar(im, extend='both', shrink=0.9, ax=ax1)
cbar.set_label('uniform')
for ticklabel in ax1.xaxis.get_ticklabels():
ticklabel.set_visible(False)
# Plot using a small number of colors, with unevenly spaced boundaries.
im = ax2.imshow(Zm, interpolation='nearest',
cmap=palette,
norm=colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1],
ncolors=palette.N),
aspect='auto',
origin='lower',
extent=[x0, x1, y0, y1])
ax2.set_title('With BoundaryNorm')
cbar = fig.colorbar(im, extend='both', spacing='proportional',
shrink=0.9, ax=ax2)
cbar.set_label('proportional')
fig.suptitle('imshow, with out-of-range and masked data')
plt.show()
```
![图像掩码示例](https://matplotlib.org/_images/sphx_glr_image_masked_001.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.colors.BoundaryNorm
matplotlib.colorbar.ColorbarBase.set_label
```
## 下载这个示例
- [下载python源码: image_masked.py](https://matplotlib.org/_downloads/image_masked.py)
- [下载Jupyter notebook: image_masked.ipynb](https://matplotlib.org/_downloads/image_masked.ipynb)

View File

@@ -0,0 +1,71 @@
# 不均匀分布图像
这说明了非统一图像类。它不是通过AXES方法提供的,但是可以很容易地将它添加到AXIS实例中,如下所示。
![图像掩码示例](https://matplotlib.org/_images/sphx_glr_image_nonuniform_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import NonUniformImage
from matplotlib import cm
interp = 'nearest'
# Linear x array for cell centers:
x = np.linspace(-4, 4, 9)
# Highly nonlinear x array:
x2 = x**3
y = np.linspace(-4, 4, 9)
z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2)
fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
fig.suptitle('NonUniformImage class', fontsize='large')
ax = axs[0, 0]
im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4),
cmap=cm.Purples)
im.set_data(x, y, z)
ax.images.append(im)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.set_title(interp)
ax = axs[0, 1]
im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4),
cmap=cm.Purples)
im.set_data(x2, y, z)
ax.images.append(im)
ax.set_xlim(-64, 64)
ax.set_ylim(-4, 4)
ax.set_title(interp)
interp = 'bilinear'
ax = axs[1, 0]
im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4),
cmap=cm.Purples)
im.set_data(x, y, z)
ax.images.append(im)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.set_title(interp)
ax = axs[1, 1]
im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4),
cmap=cm.Purples)
im.set_data(x2, y, z)
ax.images.append(im)
ax.set_xlim(-64, 64)
ax.set_ylim(-4, 4)
ax.set_title(interp)
plt.show()
```
## 下载这个示例
- [下载python源码: image_nonuniform.py](https://matplotlib.org/_downloads/image_nonuniform.py)
- [下载Jupyter notebook: image_nonuniform.ipynb](https://matplotlib.org/_downloads/image_nonuniform.ipynb)

View File

@@ -0,0 +1,136 @@
# 在二维图像中混合透明和颜色
混合透明与颜色,以突出显示部分数据与显示。
[matplotlib.pyplot.imshow()](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow)的一个常见用途是绘制二维统计图。虽然imshow可以很容易地将二维矩阵可视化为图像,但它并不容易让您为输出添加透明度。例如,可以绘制统计量(例如t统计量)并根据其p值为每个像素的透明度着色。此示例演示如何使用[matplotlib.colors.Normalize](https://matplotlib.org/api/_as_gen/matplotlib.colors.Normalize.html#matplotlib.colors.Normalize)实现此效果。 请注意,无法直接将alpha值传递给[matplotlib.pyplot.imshow()](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow)。
首先我们将生成一些数据,在这种情况下,我们将在二维网格中创建两个2维“blob”。一个blob是正面的,另一个是负面的。
```python
# sphinx_gallery_thumbnail_number = 3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
def normal_pdf(x, mean, var):
return np.exp(-(x - mean)**2 / (2*var))
# Generate the space in which the blobs will live
xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)
# Generate the blobs. The range of the values is roughly -.0002 to .0002
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]
gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])
gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])
weights_high = np.array(np.meshgrid(gauss_x_high, gauss_y_high)).prod(0)
weights_low = -1 * np.array(np.meshgrid(gauss_x_low, gauss_y_low)).prod(0)
weights = weights_high + weights_low
# We'll also create a grey background into which the pixels will fade
greys = np.empty(weights.shape + (3,), dtype=np.uint8)
greys.fill(70)
# First we'll plot these blobs using only ``imshow``.
vmax = np.abs(weights).max()
vmin = -vmax
cmap = plt.cm.RdYlBu
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, extent=(xmin, xmax, ymin, ymax), cmap=cmap)
ax.set_axis_off()
```
![在二维图像中混合透明和颜色](https://matplotlib.org/_images/sphx_glr_image_transparency_blend_001.png)
## 混合透明度
在使用[matplotlib.pyplot.imshow()](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow)绘制数据时,包含透明度的最简单方法是将二维数据数组转换为RGBA值的三维图像数组。这可以用[matplotlib.colors.Normalize](https://matplotlib.org/api/_as_gen/matplotlib.colors.Normalize.html#matplotlib.colors.Normalize)来实现。例如,我们将创建一个从左向右移动的渐变。
```python
# Create an alpha channel of linearly increasing values moving to the right.
alphas = np.ones(weights.shape)
alphas[:, 30:] = np.linspace(1, 0, 70)
# Normalize the colors b/w 0 and 1, we'll then pass an MxNx4 array to imshow
colors = Normalize(vmin, vmax, clip=True)(weights)
colors = cmap(colors)
# Now set the alpha channel to the one we created above
colors[..., -1] = alphas
# Create the figure and image
# Note that the absolute values may be slightly different
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(colors, extent=(xmin, xmax, ymin, ymax))
ax.set_axis_off()
```
![在二维图像中混合透明和颜色2](https://matplotlib.org/_images/sphx_glr_image_transparency_blend_002.png)
## 使用透明度高亮显示高振幅值
最后,我们将重新创建相同的图,但是这一次我们将使用透明来突出显示数据中的极端值。这通常用于突出显示具有较小p值的数据点。我们还将添加等高线,以突出显示图像值。评星
```python
# Create an alpha channel based on weight values
# Any value whose absolute value is > .0001 will have zero transparency
alphas = Normalize(0, .3, clip=True)(np.abs(weights))
alphas = np.clip(alphas, .4, 1) # alpha value clipped at the bottom at .4
# Normalize the colors b/w 0 and 1, we'll then pass an MxNx4 array to imshow
colors = Normalize(vmin, vmax)(weights)
colors = cmap(colors)
# Now set the alpha channel to the one we created above
colors[..., -1] = alphas
# Create the figure and image
# Note that the absolute values may be slightly different
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(colors, extent=(xmin, xmax, ymin, ymax))
# Add contour lines to further highlight different levels.
ax.contour(weights[::-1], levels=[-.1, .1], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()
ax.contour(weights[::-1], levels=[-.0001, .0001], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()
```
![在二维图像中混合透明和颜色3](https://matplotlib.org/_images/sphx_glr_image_transparency_blend_003.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.colors.Normalize
matplotlib.axes.Axes.set_axis_off
```
## 下载这个示例
- [下载python源码: image_transparency_blend.py](https://matplotlib.org/_downloads/image_transparency_blend.py)
- [下载Jupyter notebook: image_transparency_blend.ipynb](https://matplotlib.org/_downloads/image_transparency_blend.ipynb)

View File

@@ -0,0 +1,50 @@
# 修改坐标格式化程序
修改坐标格式化程序,以报告给定x和y的最近像素的图像“z”值。这个功能在默认情况下是内置的,但是展示如何自定义Format_coord函数仍然很有用。
```python
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
X = 10*np.random.rand(5, 3)
fig, ax = plt.subplots()
ax.imshow(X, interpolation='nearest')
numrows, numcols = X.shape
def format_coord(x, y):
col = int(x + 0.5)
row = int(y + 0.5)
if col >= 0 and col < numcols and row >= 0 and row < numrows:
z = X[row, col]
return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z)
else:
return 'x=%1.4f, y=%1.4f' % (x, y)
ax.format_coord = format_coord
plt.show()
```
![修改坐标格式化程序](https://matplotlib.org/_images/sphx_glr_image_zcoord_001.png)
## 参考
本例中显示了下列函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.format_coord
matplotlib.axes.Axes.imshow
```
## 下载这个示例
- [下载python源码: image_zcoord.py](https://matplotlib.org/_downloads/image_zcoord.py)
- [下载Jupyter notebook: image_zcoord.ipynb](https://matplotlib.org/_downloads/image_zcoord.ipynb)

View File

@@ -0,0 +1,50 @@
# imshow或matshow的插值
这个示例显示了[imshow()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow) 和[matshow()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.matshow.html#matplotlib.axes.Axes.matshow)的插值方法之间的区别。
如果插值为无,则默认为图像。插值RC参数。如果插值是 “none” ,则不执行插值的Agg,ps和pdf后端。其他后端将默认为“nearest”。
对于Agg、ps和pdf后端,当大图像缩小时,``interpolation = 'none'`` 工作得很好,而当小图像被放大时,interpolation = ``'interpolation = 'none'`` 则运行正常。
```python
import matplotlib.pyplot as plt
import numpy as np
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']
# Fixing random state for reproducibility
np.random.seed(19680801)
grid = np.random.rand(4, 4)
fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9.3, 6),
subplot_kw={'xticks': [], 'yticks': []})
fig.subplots_adjust(left=0.03, right=0.97, hspace=0.3, wspace=0.05)
for ax, interp_method in zip(axs.flat, methods):
ax.imshow(grid, interpolation=interp_method, cmap='viridis')
ax.set_title(str(interp_method))
plt.tight_layout()
plt.show()
```
![imshow或matshow的插值](https://matplotlib.org/_images/sphx_glr_interpolation_methods_001.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
```
## 下载这个示例
- [下载python源码: interpolation_methods.py](https://matplotlib.org/_downloads/interpolation_methods.py)
- [下载Jupyter notebook: interpolation_methods.ipynb](https://matplotlib.org/_downloads/interpolation_methods.ipynb)

View File

@@ -0,0 +1,99 @@
# 不规则空间数据的等高线图
不规则空间数据在规则网格上插值的等高线图与非结构三角形网格的三棱图的比较。
由于 [contour](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contour.html#matplotlib.axes.Axes.contour) 和 [contourf](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html#matplotlib.axes.Axes.contourf) 期望数据存在于规则网格上,因此绘制不规则间隔数据的等高线图需要不同的方法。这两个选项是:
- 首先将数据插值到常规网格。这可以通过机载装置完成,例如,通过[LinearTriInterpolator](https://matplotlib.org/api/tri_api.html#matplotlib.tri.LinearTriInterpolator)或使用外部功能,例如 通过scipy.interpolate.griddata。然后用常规的等高线绘制插值数据。
- 直接使用[tricontour](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tricontour.html#matplotlib.axes.Axes.tricontour)或[tricontourf](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tricontourf.html#matplotlib.axes.Axes.tricontourf),它将在内部进行三角测量。
此示例显示了两种方法。
```python
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
np.random.seed(19680801)
npts = 200
ngridx = 100
ngridy = 200
x = np.random.uniform(-2, 2, npts)
y = np.random.uniform(-2, 2, npts)
z = x * np.exp(-x**2 - y**2)
fig, (ax1, ax2) = plt.subplots(nrows=2)
# -----------------------
# Interpolation on a grid
# -----------------------
# A contour plot of irregularly spaced data coordinates
# via interpolation on a grid.
# Create grid values first.
xi = np.linspace(-2.1, 2.1, ngridx)
yi = np.linspace(-2.1, 2.1, ngridy)
# Perform linear interpolation of the data (x,y)
# on a grid defined by (xi,yi)
triang = tri.Triangulation(x, y)
interpolator = tri.LinearTriInterpolator(triang, z)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)
# Note that scipy.interpolate provides means to interpolate data on a grid
# as well. The following would be an alternative to the four lines above:
#from scipy.interpolate import griddata
#zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')
ax1.contour(xi, yi, zi, levels=14, linewidths=0.5, colors='k')
cntr1 = ax1.contourf(xi, yi, zi, levels=14, cmap="RdBu_r")
fig.colorbar(cntr1, ax=ax1)
ax1.plot(x, y, 'ko', ms=3)
ax1.axis((-2, 2, -2, 2))
ax1.set_title('grid and contour (%d points, %d grid points)' %
(npts, ngridx * ngridy))
# ----------
# Tricontour
# ----------
# Directly supply the unordered, irregularly spaced coordinates
# to tricontour.
ax2.tricontour(x, y, z, levels=14, linewidths=0.5, colors='k')
cntr2 = ax2.tricontourf(x, y, z, levels=14, cmap="RdBu_r")
fig.colorbar(cntr2, ax=ax2)
ax2.plot(x, y, 'ko', ms=3)
ax2.axis((-2, 2, -2, 2))
ax2.set_title('tricontour (%d points)' % npts)
plt.subplots_adjust(hspace=0.5)
plt.show()
```
![不规则空间数据的等高线图例](https://matplotlib.org/_images/sphx_glr_irregulardatagrid_001.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.contour
matplotlib.pyplot.contour
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
matplotlib.axes.Axes.tricontour
matplotlib.pyplot.tricontour
matplotlib.axes.Axes.tricontourf
matplotlib.pyplot.tricontourf
```
## 下载这个示例
- [下载python源码: irregulardatagrid.py](https://matplotlib.org/_downloads/irregulardatagrid.py)
- [下载Jupyter notebook: irregulardatagrid.ipynb](https://matplotlib.org/_downloads/irregulardatagrid.ipynb)

View File

@@ -0,0 +1,58 @@
# 图层图像
使用Alpha混合将图像层叠在彼此之上
```python
import matplotlib.pyplot as plt
import numpy as np
def func3(x, y):
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2 + y**2))
# make these smaller to increase the resolution
dx, dy = 0.05, 0.05
x = np.arange(-3.0, 3.0, dx)
y = np.arange(-3.0, 3.0, dy)
X, Y = np.meshgrid(x, y)
# when layering multiple images, the images need to have the same
# extent. This does not mean they need to have the same shape, but
# they both need to render to the same coordinate system determined by
# xmin, xmax, ymin, ymax. Note if you use different interpolations
# for the images their apparent extent could be different due to
# interpolation edge effects
extent = np.min(x), np.max(x), np.min(y), np.max(y)
fig = plt.figure(frameon=False)
Z1 = np.add.outer(range(8), range(8)) % 2 # chessboard
im1 = plt.imshow(Z1, cmap=plt.cm.gray, interpolation='nearest',
extent=extent)
Z2 = func3(X, Y)
im2 = plt.imshow(Z2, cmap=plt.cm.viridis, alpha=.9, interpolation='bilinear',
extent=extent)
plt.show()
```
![图层图像示例](https://matplotlib.org/_images/sphx_glr_layer_images_001.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
```
## 下载这个示例
- [下载python源码: layer_images.py](https://matplotlib.org/_downloads/layer_images.py)
- [下载Jupyter notebook: layer_images.ipynb](https://matplotlib.org/_downloads/layer_images.ipynb)

View File

@@ -0,0 +1,39 @@
# Matshow
简单的 matshow 例子。
```python
import matplotlib.pyplot as plt
import numpy as np
def samplemat(dims):
"""Make a matrix with all zeros and increasing elements on the diagonal"""
aa = np.zeros(dims)
for i in range(min(dims)):
aa[i, i] = i
return aa
# Display matrix
plt.matshow(samplemat((15, 15)))
plt.show()
```
![matshow示例](https://matplotlib.org/_images/sphx_glr_matshow_001.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.matshow
matplotlib.pyplot.matshow
```
## 下载这个示例
- [下载python源码: matshow.py](https://matplotlib.org/_downloads/matshow.py)
- [下载Jupyter notebook: matshow.ipynb](https://matplotlib.org/_downloads/matshow.ipynb)

View File

@@ -0,0 +1,75 @@
# 多重图像
用单一的彩色地图、标准和颜色条制作一组图像。
```python
from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
Nr = 3
Nc = 2
cmap = "cool"
fig, axs = plt.subplots(Nr, Nc)
fig.suptitle('Multiple images')
images = []
for i in range(Nr):
for j in range(Nc):
# Generate data with a range that varies from one plot to the next.
data = ((1 + i + j) / 10) * np.random.rand(10, 20) * 1e-6
images.append(axs[i, j].imshow(data, cmap=cmap))
axs[i, j].label_outer()
# Find the min and max of all colors for use in setting the color scale.
vmin = min(image.get_array().min() for image in images)
vmax = max(image.get_array().max() for image in images)
norm = colors.Normalize(vmin=vmin, vmax=vmax)
for im in images:
im.set_norm(norm)
fig.colorbar(images[0], ax=axs, orientation='horizontal', fraction=.1)
# Make images respond to changes in the norm of other images (e.g. via the
# "edit axis, curves and images parameters" GUI on Qt), but be careful not to
# recurse infinitely!
def update(changed_image):
for im in images:
if (changed_image.get_cmap() != im.get_cmap()
or changed_image.get_clim() != im.get_clim()):
im.set_cmap(changed_image.get_cmap())
im.set_clim(changed_image.get_clim())
for im in images:
im.callbacksSM.connect('changed', update)
plt.show()
```
![多重图像示例](https://matplotlib.org/_images/sphx_glr_multi_image_001.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.colors.Normalize
matplotlib.cm.ScalarMappable.set_cmap
matplotlib.cm.ScalarMappable.set_norm
matplotlib.cm.ScalarMappable.set_clim
matplotlib.cbook.CallbackRegistry.connect
```
## 下载这个示例
- [下载python源码: multi_image.py](https://matplotlib.org/_downloads/multi_image.py)
- [下载Jupyter notebook: multi_image.ipynb](https://matplotlib.org/_downloads/multi_image.ipynb)

View File

@@ -0,0 +1,133 @@
# Pcolor 演示
使用[pcolor()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.pcolor.html#matplotlib.axes.Axes.pcolor)生成图像。
Pcolor允许您生成二维图像样式图。 下面我们将在Matplotlib中展示如何做到这一点。
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
```
## 一个简单的 pcolor 示例
```python
Z = np.random.rand(6, 10)
fig, (ax0, ax1) = plt.subplots(2, 1)
c = ax0.pcolor(Z)
ax0.set_title('default: no edges')
c = ax1.pcolor(Z, edgecolors='k', linewidths=4)
ax1.set_title('thick edges')
fig.tight_layout()
plt.show()
```
![Pcolor 演示](https://matplotlib.org/_images/sphx_glr_pcolor_demo_001.png)
## 比较pcolor与类似的功能
Demonstrates similarities between pcolor(), pcolormesh(), imshow() and pcolorfast() for drawing quadrilateral grids.
```python
# make these smaller to increase the resolution
dx, dy = 0.15, 0.05
# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(-3, 3 + dy, dy),
slice(-3, 3 + dx, dx)]
z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
fig, axs = plt.subplots(2, 2)
ax = axs[0, 0]
c = ax.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolor')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)
ax = axs[0, 1]
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)
ax = axs[1, 0]
c = ax.imshow(z, cmap='RdBu', vmin=z_min, vmax=z_max,
extent=[x.min(), x.max(), y.min(), y.max()],
interpolation='nearest', origin='lower')
ax.set_title('image (nearest)')
fig.colorbar(c, ax=ax)
ax = axs[1, 1]
c = ax.pcolorfast(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolorfast')
fig.colorbar(c, ax=ax)
fig.tight_layout()
plt.show()
```
![Pcolor 演示2](https://matplotlib.org/_images/sphx_glr_pcolor_demo_002.png)
## Pcolor具有对数刻度
以下显示了具有对数刻度的pcolor图。
```python
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
# A low hump with a spike coming out.
# Needs to have z/colour axis on a log scale so we see both hump and spike.
# linear scale only shows the spike.
Z1 = np.exp(-(X)**2 - (Y)**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, (ax0, ax1) = plt.subplots(2, 1)
c = ax0.pcolor(X, Y, Z,
norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r')
fig.colorbar(c, ax=ax0)
c = ax1.pcolor(X, Y, Z, cmap='PuBu_r')
fig.colorbar(c, ax=ax1)
plt.show()
```
![Pcolor 演示3](https://matplotlib.org/_images/sphx_glr_pcolor_demo_003.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.pcolor
matplotlib.pyplot.pcolor
matplotlib.axes.Axes.pcolormesh
matplotlib.pyplot.pcolormesh
matplotlib.axes.Axes.pcolorfast
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.colors.LogNorm
```
## 下载这个示例
- [下载python源码: pcolor_demo.py](https://matplotlib.org/_downloads/pcolor_demo.py)
- [下载Jupyter notebook: pcolor_demo.ipynb](https://matplotlib.org/_downloads/pcolor_demo.ipynb)

View File

@@ -0,0 +1,75 @@
# pcolormesh
演示如何组合Normalization和Colormap实例以在[pcolor()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.pcolor.html#matplotlib.axes.Axes.pcolor),[pcolormesh()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.pcolormesh.html#matplotlib.axes.Axes.pcolormesh)和[imshow()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow)类型图中绘制“级别”,其方式与contour / contourf的levels关键字参数类似。
```python
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import numpy as np
# make these smaller to increase the resolution
dx, dy = 0.05, 0.05
# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(1, 5 + dy, dy),
slice(1, 5 + dx, dx)]
z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max())
# pick the desired colormap, sensible levels, and define a normalization
# instance which takes data values and translates those into levels.
cmap = plt.get_cmap('PiYG')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
fig, (ax0, ax1) = plt.subplots(nrows=2)
im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm)
fig.colorbar(im, ax=ax0)
ax0.set_title('pcolormesh with levels')
# contours are *point* based plots, so convert our bound into point
# centers
cf = ax1.contourf(x[:-1, :-1] + dx/2.,
y[:-1, :-1] + dy/2., z, levels=levels,
cmap=cmap)
fig.colorbar(cf, ax=ax1)
ax1.set_title('contourf with levels')
# adjust spacing between subplots so `ax1` title and `ax0` tick labels
# don't overlap
fig.tight_layout()
plt.show()
```
![pcolormesh示例](https://matplotlib.org/_images/sphx_glr_pcolormesh_levels_001.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
matplotlib.axes.Axes.pcolormesh
matplotlib.pyplot.pcolormesh
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.colors.BoundaryNorm
matplotlib.ticker.MaxNLocator
```
## 下载这个示例
- [下载python源码: pcolormesh_levels.py](https://matplotlib.org/_downloads/pcolormesh_levels.py)
- [下载Jupyter notebook: pcolormesh_levels.ipynb](https://matplotlib.org/_downloads/pcolormesh_levels.ipynb)

View File

@@ -0,0 +1,91 @@
# 流图
流图或流线图用于显示2D矢量场。此示例显示了 [streamplot()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.streamplot.html#matplotlib.axes.Axes.streamplot) 函数的一些功能:
- 沿着流线改变颜色。
- 改变流线的密度。
- 沿流线改变线宽。
- 控制流线的起点。
- 流线跳过蒙面区域和NaN值。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
w = 3
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)
fig = plt.figure(figsize=(7, 9))
gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])
# Varying density along a streamline
ax0 = fig.add_subplot(gs[0, 0])
ax0.streamplot(X, Y, U, V, density=[0.5, 1])
ax0.set_title('Varying Density')
# Varying color along a streamline
ax1 = fig.add_subplot(gs[0, 1])
strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
fig.colorbar(strm.lines)
ax1.set_title('Varying Color')
# Varying line width along a streamline
ax2 = fig.add_subplot(gs[1, 0])
lw = 5*speed / speed.max()
ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)
ax2.set_title('Varying Line Width')
# Controlling the starting points of the streamlines
seed_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1, 0, 1, 2, 2]])
ax3 = fig.add_subplot(gs[1, 1])
strm = ax3.streamplot(X, Y, U, V, color=U, linewidth=2,
cmap='autumn', start_points=seed_points.T)
fig.colorbar(strm.lines)
ax3.set_title('Controlling Starting Points')
# Displaying the starting points with blue symbols.
ax3.plot(seed_points[0], seed_points[1], 'bo')
ax3.axis((-w, w, -w, w))
# Create a mask
mask = np.zeros(U.shape, dtype=bool)
mask[40:60, 40:60] = True
U[:20, :20] = np.nan
U = np.ma.array(U, mask=mask)
ax4 = fig.add_subplot(gs[2:, :])
ax4.streamplot(X, Y, U, V, color='r')
ax4.set_title('Streamplot with Masking')
ax4.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5,
interpolation='nearest', cmap='gray', aspect='auto')
ax4.set_aspect('equal')
plt.tight_layout()
plt.show()
```
![流图示例](https://matplotlib.org/_images/sphx_glr_plot_streamplot_001.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.streamplot
matplotlib.pyplot.streamplot
matplotlib.gridspec
matplotlib.gridspec.GridSpec
Total running time of the script: ( 0 minutes 1.403 seconds)
```
## 下载这个示例
- [下载python源码: plot_streamplot.py](https://matplotlib.org/_downloads/plot_streamplot.py)
- [下载Jupyter notebook: plot_streamplot.ipynb](https://matplotlib.org/_downloads/plot_streamplot.ipynb)

View File

@@ -0,0 +1,59 @@
# QuadMesh 演示
[pcolormesh](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.pcolormesh.html#matplotlib.axes.Axes.pcolormesh) 使用[QuadMesh](https://matplotlib.org/api/collections_api.html#matplotlib.collections.QuadMesh),一种更快的 [pcolor](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.pcolor.html#matplotlib.axes.Axes.pcolor) 泛化,但有一些限制。
此演示说明了带有掩码数据的quadmesh中的误差。
```python
import copy
from matplotlib import cm, pyplot as plt
import numpy as np
n = 12
x = np.linspace(-1.5, 1.5, n)
y = np.linspace(-1.5, 1.5, n * 2)
X, Y = np.meshgrid(x, y)
Qx = np.cos(Y) - np.cos(X)
Qz = np.sin(Y) + np.sin(X)
Z = np.sqrt(X**2 + Y**2) / 5
Z = (Z - Z.min()) / (Z.max() - Z.min())
# The color array can include masked values.
Zm = np.ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z)
fig, axs = plt.subplots(nrows=1, ncols=3)
axs[0].pcolormesh(Qx, Qz, Z, shading='gouraud')
axs[0].set_title('Without masked values')
# You can control the color of the masked region. We copy the default colormap
# before modifying it.
cmap = copy.copy(cm.get_cmap(plt.rcParams['image.cmap']))
cmap.set_bad('y', 1.0)
axs[1].pcolormesh(Qx, Qz, Zm, shading='gouraud', cmap=cmap)
axs[1].set_title('With masked values')
# Or use the default, which is transparent.
axs[2].pcolormesh(Qx, Qz, Zm, shading='gouraud')
axs[2].set_title('With masked values')
fig.tight_layout()
plt.show()
```
![QuadMesh 演示](https://matplotlib.org/_images/sphx_glr_quadmesh_demo_001.png)
## 参考
下面的示例演示了以下函数和方法的使用:
```python
import matplotlib
matplotlib.axes.Axes.pcolormesh
matplotlib.pyplot.pcolormesh
```
## 下载这个示例
- [下载python源码: quadmesh_demo.py](https://matplotlib.org/_downloads/quadmesh_demo.py)
- [下载Jupyter notebook: quadmesh_demo.ipynb](https://matplotlib.org/_downloads/quadmesh_demo.ipynb)

View File

@@ -0,0 +1,65 @@
# 演示高级箭图和箭袋功能
为[箭袋]((https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.quiver.html#matplotlib.axes.Axes.quiver))展示一些更高级的选项。有关简单示例,请参阅 [Quiver Simple Demo](https://matplotlib.org/gallery/images_contours_and_fields/quiver_simple_demo.html)。
已知问题:自动缩放图未考虑箭头,因此边界上的那些通常不在图中。以完全一般的方式解决这个问题并不容易。解决方法是手动展开Axes对象。
```python
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))
U = np.cos(X)
V = np.sin(Y)
fig1, ax1 = plt.subplots()
ax1.set_title('Arrows scale with plot width, not view')
Q = ax1.quiver(X, Y, U, V, units='width')
qk = ax1.quiverkey(Q, 0.9, 0.9, 2, r'$2 \frac{m}{s}$', labelpos='E',
coordinates='figure')
```
![箭图示例](https://matplotlib.org/_images/sphx_glr_quiver_demo_001.png)
```python
fig2, ax2 = plt.subplots()
ax2.set_title("pivot='mid'; every third arrow; units='inches'")
Q = ax2.quiver(X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3],
pivot='mid', units='inches')
qk = ax2.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
coordinates='figure')
ax2.scatter(X[::3, ::3], Y[::3, ::3], color='r', s=5)
```
![箭图示例2](https://matplotlib.org/_images/sphx_glr_quiver_demo_002.png)
```python
fig3, ax3 = plt.subplots()
ax3.set_title("pivot='tip'; scales with x view")
M = np.hypot(U, V)
Q = ax3.quiver(X, Y, U, V, M, units='x', pivot='tip', width=0.022,
scale=1 / 0.15)
qk = ax3.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
coordinates='figure')
ax3.scatter(X, Y, color='k', s=5)
plt.show()
```
![箭图示例3](https://matplotlib.org/_images/sphx_glr_quiver_demo_003.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.quiver
matplotlib.pyplot.quiver
matplotlib.axes.Axes.quiverkey
matplotlib.pyplot.quiverkey
```
## 下载这个示例
- [下载python源码: quiver_demo.py](https://matplotlib.org/_downloads/quiver_demo.py)
- [下载Jupyter notebook: quiver_demo.ipynb](https://matplotlib.org/_downloads/quiver_demo.ipynb)

View File

@@ -0,0 +1,40 @@
# 箭图简单演示
带[quiverkey](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.quiver.html#matplotlib.axes.Axes.quiver)的[箭袋图](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.quiver.html#matplotlib.axes.Axes.quiver)的简单示例。
有关更高级的选项,请参阅演示[高级箭袋和quiverkey功能](https://matplotlib.org/gallery/images_contours_and_fields/quiver_demo.html)。
```python
import matplotlib.pyplot as plt
import numpy as np
X = np.arange(-10, 10, 1)
Y = np.arange(-10, 10, 1)
U, V = np.meshgrid(X, Y)
fig, ax = plt.subplots()
q = ax.quiver(X, Y, U, V)
ax.quiverkey(q, X=0.3, Y=1.1, U=10,
label='Quiver key, length = 10', labelpos='E')
plt.show()
```
![箭图简单演示](https://matplotlib.org/_images/sphx_glr_quiver_simple_demo_001.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.quiver
matplotlib.pyplot.quiver
matplotlib.axes.Axes.quiverkey
matplotlib.pyplot.quiverkey
```
## 下载这个示例
- [下载python源码: quiver_simple_demo.py](https://matplotlib.org/_downloads/quiver_simple_demo.py)
- [下载Jupyter notebook: quiver_simple_demo.ipynb](https://matplotlib.org/_downloads/quiver_simple_demo.ipynb)

View File

@@ -0,0 +1,78 @@
# 着色示例
显示如何制作阴影浮雕图的示例,如Mathematica (http://reference.wolfram.com/mathematica/ref/ReliefPlot.html)或通用映射工具(https://gmt.soest.hawaii.edu/)
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LightSource
from matplotlib.cbook import get_sample_data
def main():
# Test data
x, y = np.mgrid[-5:5:0.05, -5:5:0.05]
z = 5 * (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2))
filename = get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
with np.load(filename) as dem:
elev = dem['elevation']
fig = compare(z, plt.cm.copper)
fig.suptitle('HSV Blending Looks Best with Smooth Surfaces', y=0.95)
fig = compare(elev, plt.cm.gist_earth, ve=0.05)
fig.suptitle('Overlay Blending Looks Best with Rough Surfaces', y=0.95)
plt.show()
def compare(z, cmap, ve=1):
# Create subplots and hide ticks
fig, axs = plt.subplots(ncols=2, nrows=2)
for ax in axs.flat:
ax.set(xticks=[], yticks=[])
# Illuminate the scene from the northwest
ls = LightSource(azdeg=315, altdeg=45)
axs[0, 0].imshow(z, cmap=cmap)
axs[0, 0].set(xlabel='Colormapped Data')
axs[0, 1].imshow(ls.hillshade(z, vert_exag=ve), cmap='gray')
axs[0, 1].set(xlabel='Illumination Intensity')
rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='hsv')
axs[1, 0].imshow(rgb)
axs[1, 0].set(xlabel='Blend Mode: "hsv" (default)')
rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='overlay')
axs[1, 1].imshow(rgb)
axs[1, 1].set(xlabel='Blend Mode: "overlay"')
return fig
if __name__ == '__main__':
main()
```
![着色示例](https://matplotlib.org/_images/sphx_glr_shading_example_001.png)
![着色示例2](https://matplotlib.org/_images/sphx_glr_shading_example_002.png)
## 参考
本例中显示了以下函数、方法和类的使用:
```python
import matplotlib
matplotlib.colors.LightSource
matplotlib.axes.Axes.imshow
matplotlib.pyplot.imshow
```
## 下载这个示例
- [下载python源码: shading_example.py](https://matplotlib.org/_downloads/shading_example.py)
- [下载Jupyter notebook: shading_example.ipynb](https://matplotlib.org/_downloads/shading_example.ipynb)

View File

@@ -0,0 +1,54 @@
# 频谱图演示
频谱图的演示 ([specgram()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.specgram.html#matplotlib.axes.Axes.specgram))。
```python
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
dt = 0.0005
t = np.arange(0.0, 20.0, dt)
s1 = np.sin(2 * np.pi * 100 * t)
s2 = 2 * np.sin(2 * np.pi * 400 * t)
# create a transient "chirp"
mask = np.where(np.logical_and(t > 10, t < 12), 1.0, 0.0)
s2 = s2 * mask
# add some noise into the mix
nse = 0.01 * np.random.random(size=len(t))
x = s1 + s2 + nse # the signal
NFFT = 1024 # the length of the windowing segments
Fs = int(1.0 / dt) # the sampling frequency
fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(t, x)
Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
# The `specgram` method returns 4 objects. They are:
# - Pxx: the periodogram
# - freqs: the frequency vector
# - bins: the centers of the time bins
# - im: the matplotlib.image.AxesImage instance representing the data in the plot
plt.show()
```
![频谱图示例](https://matplotlib.org/_images/sphx_glr_specgram_demo_001.png)
## 参考
此示例中显示了以下函数的使用方法:
```python
import matplotlib
matplotlib.axes.Axes.specgram
matplotlib.pyplot.specgram
```
## 下载这个示例
- [下载python源码: specgram_demo.py](https://matplotlib.org/_downloads/specgram_demo.py)
- [下载Jupyter notebook: specgram_demo.ipynb](https://matplotlib.org/_downloads/specgram_demo.ipynb)

View File

@@ -0,0 +1,43 @@
# Spy 演示
绘制数组的稀疏模式。
```python
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 2)
ax1 = axs[0, 0]
ax2 = axs[0, 1]
ax3 = axs[1, 0]
ax4 = axs[1, 1]
x = np.random.randn(20, 20)
x[5, :] = 0.
x[:, 12] = 0.
ax1.spy(x, markersize=5)
ax2.spy(x, precision=0.1, markersize=5)
ax3.spy(x)
ax4.spy(x, precision=0.1)
plt.show()
```
![Spy 演示](https://matplotlib.org/_images/sphx_glr_spy_demos_001.png)
## 参考
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.spy
matplotlib.pyplot.spy
```
## 下载这个示例
- [下载python源码: spy_demos.py](https://matplotlib.org/_downloads/spy_demos.py)
- [下载Jupyter notebook: spy_demos.ipynb](https://matplotlib.org/_downloads/spy_demos.ipynb)

View File

@@ -0,0 +1,128 @@
# Tricontour 演示
非结构化三角形网格的等高线图。
```python
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
```
在不指定三角形的情况下创建三角剖分会导致点的Delaunay三角剖分。
```python
# First create the x and y coordinates of the points.
n_angles = 48
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
z = (np.cos(radii) * np.cos(3 * angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
```
pcolor 绘图。
```python
fig1, ax1 = plt.subplots()
ax1.set_aspect('equal')
tcf = ax1.tricontourf(triang, z)
fig1.colorbar(tcf)
ax1.tricontour(triang, z, colors='k')
ax1.set_title('Contour plot of Delaunay triangulation')
```
![Tricontour 演示](https://matplotlib.org/_images/sphx_glr_tricontour_demo_001.png)
您可以指定自己的三角剖分而不是执行点的Delaunay三角剖分,其中每个三角形由构成三角形的三个点的索引给出,以顺时针或逆时针方式排序。
```python
xy = np.asarray([
[-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890],
[-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898],
[-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
[-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
[-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
[-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
[-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
[-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
[-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
[-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005],
[-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987],
[-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968],
[-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926],
[ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905],
[ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886],
[ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879],
[-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872],
[-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933],
[-0.077, 0.990], [-0.059, 0.993]])
x = np.degrees(xy[:, 0])
y = np.degrees(xy[:, 1])
x0 = -5
y0 = 52
z = np.exp(-0.01 * ((x - x0) * (x - x0) + (y - y0) * (y - y0)))
triangles = np.asarray([
[67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64],
[60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63],
[57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68],
[ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7],
[ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9],
[54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12],
[69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71],
[52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71],
[49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
[48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
[21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
[20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
[42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38],
[33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]])
```
而不是创建Triangulation对象,可以直接将x,y和三角形数组传递给tripcolor。 如果要多次使用相同的三角测量来保存重复计算,最好使用Triangulation对象。
```python
fig2, ax2 = plt.subplots()
ax2.set_aspect('equal')
tcf = ax2.tricontourf(x, y, triangles, z)
fig2.colorbar(tcf)
ax2.set_title('Contour plot of user-specified triangulation')
ax2.set_xlabel('Longitude (degrees)')
ax2.set_ylabel('Latitude (degrees)')
plt.show()
```
![Tricontour 演示2](https://matplotlib.org/_images/sphx_glr_tricontour_demo_002.png)
## 参考
此示例中显示了以下函数,方法和类的使用:
```python
import matplotlib
matplotlib.axes.Axes.tricontourf
matplotlib.pyplot.tricontourf
matplotlib.tri.Triangulation
```
## 下载这个示例
- [下载python源码: tricontour_demo.py](https://matplotlib.org/_downloads/tricontour_demo.py)
- [下载Jupyter notebook: tricontour_demo.ipynb](https://matplotlib.org/_downloads/tricontour_demo.ipynb)

View File

@@ -0,0 +1,155 @@
# Tricontour 德洛内三角
演示一组随机点的高分辨率三视图;[matplotlib.tri.TriAnalyzer](https://matplotlib.org/api/tri_api.html#matplotlib.tri.TriAnalyzer)用于提高绘图质量。
该演示的初始数据点和三角形网格如下:
- 在[-1, 1] x [-1, 1] 正方形内实例化一组随机点。
- 然后计算这些点的Delaunay三角剖分,其中一个随机三角形子集由用户隐藏(基于init_mASK_frac参数)。这将模拟无效数据。
为获得这类数据集的高分辨率轮廓而提出的通用程序如下:
1. 使用[matplotlib.tri.TriAnalyzer](https://matplotlib.org/api/tri_api.html#matplotlib.tri.TriAnalyzer)计算扩展掩码,该掩码将从三角剖分的边框中排除形状不佳(平坦)的三角形。将掩码应用于三角剖分(使用SET_MASK)。
1. 使用[matplotlib.tri.UniformTriRefiner](https://matplotlib.org/api/tri_api.html#matplotlib.tri.UniformTriRefiner)对数据进行细化和插值。
1. 用[tricontour](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tricontour.html#matplotlib.axes.Axes.tricontour)绘制精确的数据。
```python
from matplotlib.tri import Triangulation, TriAnalyzer, UniformTriRefiner
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
#-----------------------------------------------------------------------------
# Analytical test function
#-----------------------------------------------------------------------------
def experiment_res(x, y):
""" An analytic function representing experiment results """
x = 2. * x
r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
theta1 = np.arctan2(0.5 - x, 0.5 - y)
r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
z = (4 * (np.exp((r1 / 10)**2) - 1) * 30. * np.cos(3 * theta1) +
(np.exp((r2 / 10)**2) - 1) * 30. * np.cos(5 * theta2) +
2 * (x**2 + y**2))
return (np.max(z) - z) / (np.max(z) - np.min(z))
#-----------------------------------------------------------------------------
# Generating the initial data test points and triangulation for the demo
#-----------------------------------------------------------------------------
# User parameters for data test points
n_test = 200 # Number of test data points, tested from 3 to 5000 for subdiv=3
subdiv = 3 # Number of recursive subdivisions of the initial mesh for smooth
# plots. Values >3 might result in a very high number of triangles
# for the refine mesh: new triangles numbering = (4**subdiv)*ntri
init_mask_frac = 0.0 # Float > 0. adjusting the proportion of
# (invalid) initial triangles which will be masked
# out. Enter 0 for no mask.
min_circle_ratio = .01 # Minimum circle ratio - border triangles with circle
# ratio below this will be masked if they touch a
# border. Suggested value 0.01; use -1 to keep
# all triangles.
# Random points
random_gen = np.random.RandomState(seed=19680801)
x_test = random_gen.uniform(-1., 1., size=n_test)
y_test = random_gen.uniform(-1., 1., size=n_test)
z_test = experiment_res(x_test, y_test)
# meshing with Delaunay triangulation
tri = Triangulation(x_test, y_test)
ntri = tri.triangles.shape[0]
# Some invalid data are masked out
mask_init = np.zeros(ntri, dtype=bool)
masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac))
mask_init[masked_tri] = True
tri.set_mask(mask_init)
#-----------------------------------------------------------------------------
# Improving the triangulation before high-res plots: removing flat triangles
#-----------------------------------------------------------------------------
# masking badly shaped triangles at the border of the triangular mesh.
mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio)
tri.set_mask(mask)
# refining the data
refiner = UniformTriRefiner(tri)
tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv)
# analytical 'results' for comparison
z_expected = experiment_res(tri_refi.x, tri_refi.y)
# for the demo: loading the 'flat' triangles for plot
flat_tri = Triangulation(x_test, y_test)
flat_tri.set_mask(~mask)
#-----------------------------------------------------------------------------
# Now the plots
#-----------------------------------------------------------------------------
# User options for plots
plot_tri = True # plot of base triangulation
plot_masked_tri = True # plot of excessively flat excluded triangles
plot_refi_tri = False # plot of refined triangulation
plot_expected = False # plot of analytical function values for comparison
# Graphical options for tricontouring
levels = np.arange(0., 1., 0.025)
cmap = cm.get_cmap(name='Blues', lut=None)
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_title("Filtering a Delaunay mesh\n" +
"(application to high-resolution tricontouring)")
# 1) plot of the refined (computed) data contours:
ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
linewidths=[2.0, 0.5, 1.0, 0.5])
# 2) plot of the expected (analytical) data contours (dashed):
if plot_expected:
ax.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap,
linestyles='--')
# 3) plot of the fine mesh on which interpolation was done:
if plot_refi_tri:
ax.triplot(tri_refi, color='0.97')
# 4) plot of the initial 'coarse' mesh:
if plot_tri:
ax.triplot(tri, color='0.7')
# 4) plot of the unvalidated triangles from naive Delaunay Triangulation:
if plot_masked_tri:
ax.triplot(flat_tri, color='red')
plt.show()
```
![Tricontour 德洛内三角](https://matplotlib.org/_images/sphx_glr_tricontour_smooth_delaunay_001.png)
## 参考
本例中显示了下列函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.tricontour
matplotlib.pyplot.tricontour
matplotlib.axes.Axes.tricontourf
matplotlib.pyplot.tricontourf
matplotlib.axes.Axes.triplot
matplotlib.pyplot.triplot
matplotlib.tri
matplotlib.tri.Triangulation
matplotlib.tri.TriAnalyzer
matplotlib.tri.UniformTriRefiner
```
## 下载这个示例
- [下载python源码: tricontour_smooth_delaunay.py](https://matplotlib.org/_downloads/tricontour_smooth_delaunay.py)
- [下载Jupyter notebook: tricontour_smooth_delaunay.ipynb](https://matplotlib.org/_downloads/tricontour_smooth_delaunay.ipynb)

View File

@@ -0,0 +1,98 @@
# Tricontour Smooth User
使用 [matplotlib.tri.UniformTriRefiner](https://matplotlib.org/api/tri_api.html#matplotlib.tri.UniformTriRefiner) 在用户定义的三角形网格上演示高分辨率三角形。
```python
import matplotlib.tri as tri
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
#-----------------------------------------------------------------------------
# Analytical test function
#-----------------------------------------------------------------------------
def function_z(x, y):
""" A function of 2 variables """
r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
theta1 = np.arctan2(0.5 - x, 0.5 - y)
r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
z = -(2 * (np.exp((r1 / 10)**2) - 1) * 30. * np.cos(7. * theta1) +
(np.exp((r2 / 10)**2) - 1) * 30. * np.cos(11. * theta2) +
0.7 * (x**2 + y**2))
return (np.max(z) - z) / (np.max(z) - np.min(z))
#-----------------------------------------------------------------------------
# Creating a Triangulation
#-----------------------------------------------------------------------------
# First create the x and y coordinates of the points.
n_angles = 20
n_radii = 10
min_radius = 0.15
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
z = function_z(x, y)
# Now create the Triangulation.
# (Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.)
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
#-----------------------------------------------------------------------------
# Refine data
#-----------------------------------------------------------------------------
refiner = tri.UniformTriRefiner(triang)
tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3)
#-----------------------------------------------------------------------------
# Plot the triangulation and the high-res iso-contours
#-----------------------------------------------------------------------------
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.triplot(triang, lw=0.5, color='white')
levels = np.arange(0., 1., 0.025)
cmap = cm.get_cmap(name='terrain', lut=None)
ax.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
ax.tricontour(tri_refi, z_test_refi, levels=levels,
colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
linewidths=[1.0, 0.5, 0.5, 0.5, 0.5])
ax.set_title("High-resolution tricontouring")
plt.show()
```
![Tricontour Smooth User](https://matplotlib.org/_images/sphx_glr_tricontour_smooth_user_001.png)
## 参考
本例中显示了下列函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.tricontour
matplotlib.pyplot.tricontour
matplotlib.axes.Axes.tricontourf
matplotlib.pyplot.tricontourf
matplotlib.tri
matplotlib.tri.Triangulation
matplotlib.tri.UniformTriRefiner
```
## 下载这个示例
- [下载python源码: tricontour_smooth_user.py](https://matplotlib.org/_downloads/tricontour_smooth_user.py)
- [下载Jupyter notebook: tricontour_smooth_user.ipynb](https://matplotlib.org/_downloads/tricontour_smooth_user.ipynb)

View File

@@ -0,0 +1,112 @@
# Trigradient 演示
使用 [matplotlib.tri.CubicTriInterpolator](https://matplotlib.org/api/tri_api.html#matplotlib.tri.CubicTriInterpolator) 演示梯度计算。
```python
from matplotlib.tri import (
Triangulation, UniformTriRefiner, CubicTriInterpolator)
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
#-----------------------------------------------------------------------------
# Electrical potential of a dipole
#-----------------------------------------------------------------------------
def dipole_potential(x, y):
""" The electric dipole potential V """
r_sq = x**2 + y**2
theta = np.arctan2(y, x)
z = np.cos(theta)/r_sq
return (np.max(z) - z) / (np.max(z) - np.min(z))
#-----------------------------------------------------------------------------
# Creating a Triangulation
#-----------------------------------------------------------------------------
# First create the x and y coordinates of the points.
n_angles = 30
n_radii = 10
min_radius = 0.2
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
V = dipole_potential(x, y)
# Create the Triangulation; no triangles specified so Delaunay triangulation
# created.
triang = Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
#-----------------------------------------------------------------------------
# Refine data - interpolates the electrical potential V
#-----------------------------------------------------------------------------
refiner = UniformTriRefiner(triang)
tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)
#-----------------------------------------------------------------------------
# Computes the electrical field (Ex, Ey) as gradient of electrical potential
#-----------------------------------------------------------------------------
tci = CubicTriInterpolator(triang, -V)
# Gradient requested here at the mesh nodes but could be anywhere else:
(Ex, Ey) = tci.gradient(triang.x, triang.y)
E_norm = np.sqrt(Ex**2 + Ey**2)
#-----------------------------------------------------------------------------
# Plot the triangulation, the potential iso-contours and the vector field
#-----------------------------------------------------------------------------
fig, ax = plt.subplots()
ax.set_aspect('equal')
# Enforce the margins, and enlarge them to give room for the vectors.
ax.use_sticky_edges = False
ax.margins(0.07)
ax.triplot(triang, color='0.8')
levels = np.arange(0., 1., 0.01)
cmap = cm.get_cmap(name='hot', lut=None)
ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
linewidths=[2.0, 1.0, 1.0, 1.0])
# Plots direction of the electrical vector field
ax.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
units='xy', scale=10., zorder=3, color='blue',
width=0.007, headwidth=3., headlength=4.)
ax.set_title('Gradient plot: an electrical dipole')
plt.show()
```
![Trigradient 演示](https://matplotlib.org/_images/sphx_glr_trigradient_demo_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.tricontour
matplotlib.pyplot.tricontour
matplotlib.axes.Axes.triplot
matplotlib.pyplot.triplot
matplotlib.tri
matplotlib.tri.Triangulation
matplotlib.tri.CubicTriInterpolator
matplotlib.tri.CubicTriInterpolator.gradient
matplotlib.tri.UniformTriRefiner
matplotlib.axes.Axes.quiver
matplotlib.pyplot.quiver
```
## 下载这个示例
- [下载python源码: trigradient_demo.py](https://matplotlib.org/_downloads/trigradient_demo.py)
- [下载Jupyter notebook: trigradient_demo.ipynb](https://matplotlib.org/_downloads/trigradient_demo.ipynb)

View File

@@ -0,0 +1,86 @@
# Triinterp 演示
从三角网格到四边形网格的插值。
```python
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
# Create triangulation.
x = np.asarray([0, 1, 2, 3, 0.5, 1.5, 2.5, 1, 2, 1.5])
y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0])
triangles = [[0, 1, 4], [1, 2, 5], [2, 3, 6], [1, 5, 4], [2, 6, 5], [4, 5, 7],
[5, 6, 8], [5, 8, 7], [7, 8, 9]]
triang = mtri.Triangulation(x, y, triangles)
# Interpolate to regularly-spaced quad grid.
z = np.cos(1.5 * x) * np.cos(1.5 * y)
xi, yi = np.meshgrid(np.linspace(0, 3, 20), np.linspace(0, 3, 20))
interp_lin = mtri.LinearTriInterpolator(triang, z)
zi_lin = interp_lin(xi, yi)
interp_cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
zi_cubic_geom = interp_cubic_geom(xi, yi)
interp_cubic_min_E = mtri.CubicTriInterpolator(triang, z, kind='min_E')
zi_cubic_min_E = interp_cubic_min_E(xi, yi)
# Set up the figure
fig, axs = plt.subplots(nrows=2, ncols=2)
axs = axs.flatten()
# Plot the triangulation.
axs[0].tricontourf(triang, z)
axs[0].triplot(triang, 'ko-')
axs[0].set_title('Triangular grid')
# Plot linear interpolation to quad grid.
axs[1].contourf(xi, yi, zi_lin)
axs[1].plot(xi, yi, 'k-', lw=0.5, alpha=0.5)
axs[1].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5)
axs[1].set_title("Linear interpolation")
# Plot cubic interpolation to quad grid, kind=geom
axs[2].contourf(xi, yi, zi_cubic_geom)
axs[2].plot(xi, yi, 'k-', lw=0.5, alpha=0.5)
axs[2].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5)
axs[2].set_title("Cubic interpolation,\nkind='geom'")
# Plot cubic interpolation to quad grid, kind=min_E
axs[3].contourf(xi, yi, zi_cubic_min_E)
axs[3].plot(xi, yi, 'k-', lw=0.5, alpha=0.5)
axs[3].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5)
axs[3].set_title("Cubic interpolation,\nkind='min_E'")
fig.tight_layout()
plt.show()
```
![Triinterp 演示](https://matplotlib.org/_images/sphx_glr_triinterp_demo_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.tricontourf
matplotlib.pyplot.tricontourf
matplotlib.axes.Axes.triplot
matplotlib.pyplot.triplot
matplotlib.axes.Axes.contourf
matplotlib.pyplot.contourf
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
matplotlib.tri
matplotlib.tri.LinearTriInterpolator
matplotlib.tri.CubicTriInterpolator
matplotlib.tri.Triangulation
```
## 下载这个示例
- [下载python源码: triinterp_demo.py](https://matplotlib.org/_downloads/triinterp_demo.py)
- [下载Jupyter notebook: triinterp_demo.ipynb](https://matplotlib.org/_downloads/triinterp_demo.ipynb)

View File

@@ -0,0 +1,143 @@
# Tripcolor Demo
非结构化三角形网格的伪彩色图。
```python
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
```
在不指定三角形的情况下创建三角剖分会导致点的Delaunay三角剖分。
```python
# First create the x and y coordinates of the points.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
z = (np.cos(radii) * np.cos(3 * angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
```
tripcolor plot.
```python
fig1, ax1 = plt.subplots()
ax1.set_aspect('equal')
tpc = ax1.tripcolor(triang, z, shading='flat')
fig1.colorbar(tpc)
ax1.set_title('tripcolor of Delaunay triangulation, flat shading')
```
![Tripcolor 演示](https://matplotlib.org/_images/sphx_glr_tripcolor_demo_001.png)
说明Gouraud阴影。
```python
fig2, ax2 = plt.subplots()
ax2.set_aspect('equal')
tpc = ax2.tripcolor(triang, z, shading='gouraud')
fig2.colorbar(tpc)
ax2.set_title('tripcolor of Delaunay triangulation, gouraud shading')
```
![Tripcolor 演示2](https://matplotlib.org/_images/sphx_glr_tripcolor_demo_002.png)
您可以指定自己的三角剖分而不是执行点的Delaunay三角剖分,其中每个三角形由构成三角形的三个点的索引给出,以顺时针或逆时针方式排序。
```python
xy = np.asarray([
[-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890],
[-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898],
[-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
[-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
[-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
[-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
[-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
[-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
[-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
[-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005],
[-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987],
[-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968],
[-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926],
[ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905],
[ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886],
[ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879],
[-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872],
[-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933],
[-0.077, 0.990], [-0.059, 0.993]])
x, y = np.rad2deg(xy).T
triangles = np.asarray([
[67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64],
[60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63],
[57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68],
[ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7],
[ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9],
[54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12],
[69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71],
[52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71],
[49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
[48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
[21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
[20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
[42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38],
[33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]])
xmid = x[triangles].mean(axis=1)
ymid = y[triangles].mean(axis=1)
x0 = -5
y0 = 52
zfaces = np.exp(-0.01 * ((xmid - x0) * (xmid - x0) +
(ymid - y0) * (ymid - y0)))
```
而不是创建Triangulation对象,可以直接将x,y和三角形数组传递给tripcolor。 如果要多次使用相同的三角测量来保存重复计算,最好使用Triangulation对象。 通过使用facecolors kwarg,可以为每个面指定一个颜色值,而不是每个点指定一个颜色值。
```python
fig3, ax3 = plt.subplots()
ax3.set_aspect('equal')
tpc = ax3.tripcolor(x, y, triangles, facecolors=zfaces, edgecolors='k')
fig3.colorbar(tpc)
ax3.set_title('tripcolor of user-specified triangulation')
ax3.set_xlabel('Longitude (degrees)')
ax3.set_ylabel('Latitude (degrees)')
plt.show()
```
![Tripcolor 演示3](https://matplotlib.org/_images/sphx_glr_tripcolor_demo_003.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.tripcolor
matplotlib.pyplot.tripcolor
matplotlib.tri
matplotlib.tri.Triangulation
```
## 下载这个示例
- [下载python源码: tripcolor_demo.py](https://matplotlib.org/_downloads/tripcolor_demo.py)
- [下载Jupyter notebook: tripcolor_demo.ipynb](https://matplotlib.org/_downloads/tripcolor_demo.ipynb)

View File

@@ -0,0 +1,122 @@
# Triplot Demo
创建和绘制非结构化三角形网格。
```python
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
```
在不指定三角形的情况下创建三角剖分会导致点的Delaunay三角剖分。
```python
# First create the x and y coordinates of the points.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
```
绘制三角测量。
```python
fig1, ax1 = plt.subplots()
ax1.set_aspect('equal')
ax1.triplot(triang, 'bo-', lw=1)
ax1.set_title('triplot of Delaunay triangulation')
```
![Triplot 演示](https://matplotlib.org/_images/sphx_glr_triplot_demo_001.png)
您可以指定自己的三角剖分而不是执行点的Delaunay三角剖分,其中每个三角形由构成三角形的三个点的索引给出,以顺时针或逆时针方式排序。
```python
xy = np.asarray([
[-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890],
[-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898],
[-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
[-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
[-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
[-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
[-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
[-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
[-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
[-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005],
[-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987],
[-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968],
[-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926],
[ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905],
[ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886],
[ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879],
[-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872],
[-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933],
[-0.077, 0.990], [-0.059, 0.993]])
x = np.degrees(xy[:, 0])
y = np.degrees(xy[:, 1])
triangles = np.asarray([
[67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64],
[60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63],
[57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68],
[ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7],
[ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9],
[54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12],
[69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71],
[52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71],
[49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
[48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
[21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
[20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
[42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38],
[33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]])
```
而不是创建Triangulation对象,可以直接将x,y和三角形数组传递给triplot。 如果要多次使用相同的三角测量来保存重复计算,最好使用Triangulation对象。
```python
fig2, ax2 = plt.subplots()
ax2.set_aspect('equal')
ax2.triplot(x, y, triangles, 'go-', lw=1.0)
ax2.set_title('triplot of user-specified triangulation')
ax2.set_xlabel('Longitude (degrees)')
ax2.set_ylabel('Latitude (degrees)')
plt.show()
```
![Triplot 演示2](https://matplotlib.org/_images/sphx_glr_triplot_demo_002.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.triplot
matplotlib.pyplot.triplot
matplotlib.tri
matplotlib.tri.Triangulation
```
## 下载这个示例
- [下载python源码: triplot_demo.py](https://matplotlib.org/_downloads/triplot_demo.py)
- [下载Jupyter notebook: triplot_demo.ipynb](https://matplotlib.org/_downloads/triplot_demo.ipynb)

View File

@@ -0,0 +1,52 @@
# 图像水印
使用PNG文件作为水印。
```python
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.image as image
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.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 channel
fig, ax = plt.subplots()
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()
```
![图像水印示例](https://matplotlib.org/_images/sphx_glr_watermark_image_001.png)
Out:
```sh
loading /home/tcaswell/mc3/envs/dd37/lib/python3.7/site-packages/matplotlib/mpl-data/sample_data/logo2.png
```
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.image
matplotlib.image.imread
matplotlib.pyplot.imread
matplotlib.figure.Figure.figimage
```
## 下载这个示例
- [下载python源码: watermark_image.py](https://matplotlib.org/_downloads/watermark_image.py)
- [下载Jupyter notebook: watermark_image.ipynb](https://matplotlib.org/_downloads/watermark_image.ipynb)