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,86 @@
# 对齐y标签
这里显示了两种方法,一种是使用对 [Figure.align_ylabels](https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.align_ylabels) 的简短调用,另一种是使用手动方式来对齐标签。
```python
import numpy as np
import matplotlib.pyplot as plt
def make_plot(axs):
box = dict(facecolor='yellow', pad=5, alpha=0.2)
# Fixing random state for reproducibility
np.random.seed(19680801)
ax1 = axs[0, 0]
ax1.plot(2000*np.random.rand(10))
ax1.set_title('ylabels not aligned')
ax1.set_ylabel('misaligned 1', bbox=box)
ax1.set_ylim(0, 2000)
ax3 = axs[1, 0]
ax3.set_ylabel('misaligned 2', bbox=box)
ax3.plot(np.random.rand(10))
ax2 = axs[0, 1]
ax2.set_title('ylabels aligned')
ax2.plot(2000*np.random.rand(10))
ax2.set_ylabel('aligned 1', bbox=box)
ax2.set_ylim(0, 2000)
ax4 = axs[1, 1]
ax4.plot(np.random.rand(10))
ax4.set_ylabel('aligned 2', bbox=box)
# Plot 1:
fig, axs = plt.subplots(2, 2)
fig.subplots_adjust(left=0.2, wspace=0.6)
make_plot(axs)
# just align the last column of axes:
fig.align_ylabels(axs[:, 1])
plt.show()
```
![对齐y标签示例](https://matplotlib.org/_images/sphx_glr_align_ylabels_0011.png)
> 另见 Figure.align_ylabels and Figure.align_labels for a direct method of doing the same thing. Also Aligning Labels
或者我们可以使用y轴对象的set_label_coords方法手动在子图之间手动对齐轴标签。请注意这需要我们知道硬编码的良好偏移值。
```python
fig, axs = plt.subplots(2, 2)
fig.subplots_adjust(left=0.2, wspace=0.6)
make_plot(axs)
labelx = -0.3 # axes coords
for j in range(2):
axs[j, 1].yaxis.set_label_coords(labelx, 0.5)
plt.show()
```
![对齐y标签示例2](https://matplotlib.org/_images/sphx_glr_align_ylabels_002.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.figure.Figure.align_ylabels
matplotlib.axis.Axis.set_label_coords
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
matplotlib.axes.Axes.set_title
matplotlib.axes.Axes.set_ylabel
matplotlib.axes.Axes.set_ylim
```
## 下载这个示例
- [下载python源码: align_ylabels.py](https://matplotlib.org/_downloads/align_ylabels.py)
- [下载Jupyter notebook: align_ylabels.ipynb](https://matplotlib.org/_downloads/align_ylabels.ipynb)

View File

@@ -0,0 +1,57 @@
# 注释变换
此示例显示如何使用不同的坐标系进行注释。 有关注释功能的完整概述,另请参阅[注释教程](https://matplotlib.org/tutorials/text/annotations.html)。
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
xdata, ydata = 5, 0
xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))
bbox = dict(boxstyle="round", fc="0.8")
arrowprops = dict(
arrowstyle = "->",
connectionstyle = "angle,angleA=0,angleB=90,rad=10")
offset = 72
ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),
(xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
bbox=bbox, arrowprops=arrowprops)
disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),
(xdisplay, ydisplay), xytext=(0.5*offset, -offset),
xycoords='figure pixels',
textcoords='offset points',
bbox=bbox, arrowprops=arrowprops)
plt.show()
```
![注释变换示例](https://matplotlib.org/_images/sphx_glr_annotate_transform_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.transforms.Transform.transform_point
matplotlib.axes.Axes.annotate
matplotlib.pyplot.annotate
```
## 下载这个示例
- [下载python源码: annotate_transform.py](https://matplotlib.org/_downloads/annotate_transform.py)
- [下载Jupyter notebook: annotate_transform.ipynb](https://matplotlib.org/_downloads/annotate_transform.ipynb)

View File

@@ -0,0 +1,39 @@
# 注释一个图像
此示例显示如何使用指向提供的坐标的箭头注释绘图。我们修改箭头的默认值,以“缩小”它。
有关注释功能的完整概述,另请参阅[注释教程](https://matplotlib.org/tutorials/text/annotations.html)。
```python
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
ax.set_ylim(-2, 2)
plt.show()
```
![注释图像示例](https://matplotlib.org/_images/sphx_glr_annotation_basic_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.annotate
matplotlib.pyplot.annotate
```
## 下载这个示例
- [下载python源码: annotation_basic.py](https://matplotlib.org/_downloads/annotation_basic.py)
- [下载Jupyter notebook: annotation_basic.ipynb](https://matplotlib.org/_downloads/annotation_basic.ipynb)

View File

@@ -0,0 +1,47 @@
# 注释极坐标
此示例显示如何在极坐标图上创建注释。
有关注释功能的完整概述,另请参阅[注释教程](https://matplotlib.org/tutorials/text/annotations.html)。
```python
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
r = np.arange(0,1,0.001)
theta = 2 * 2*np.pi * r
line, = ax.plot(theta, r, color='#ee8d18', lw=3)
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
ax.annotate('a polar annotation',
xy=(thistheta, thisr), # theta, radius
xytext=(0.05, 0.05), # fraction, fraction
textcoords='figure fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left',
verticalalignment='bottom',
)
plt.show()
```
![注释极坐标](https://matplotlib.org/_images/sphx_glr_annotation_polar_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.projections.polar
matplotlib.axes.Axes.annotate
matplotlib.pyplot.annotate
```
## 下载这个示例
- [下载python源码: annotation_polar.py](https://matplotlib.org/_downloads/annotation_polar.py)
- [下载Jupyter notebook: annotation_polar.ipynb](https://matplotlib.org/_downloads/annotation_polar.ipynb)

View File

@@ -0,0 +1,58 @@
# 自动调整子图
自动调整子图参数。 此示例显示了一种使用[draw_event](https://matplotlib.org/users/event_handling.html)上的回调从ticklabels范围确定subplot参数的方法。
请注意,使用[tight_layout](https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.tight_layout)或 ``constrained_layout`` 可以实现类似的结果; 此示例显示了如何自定义子图参数调整。
```python
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))
def on_draw(event):
bboxes = []
for label in labels:
bbox = label.get_window_extent()
# the figure transform goes from relative coords->pixels and we
# want the inverse of that
bboxi = bbox.inverse_transformed(fig.transFigure)
bboxes.append(bboxi)
# this is the bbox that bounds all the bboxes, again in relative
# figure coords
bbox = mtransforms.Bbox.union(bboxes)
if fig.subplotpars.left < bbox.width:
# we need to move it over
fig.subplots_adjust(left=1.1*bbox.width) # pad a little
fig.canvas.draw()
return False
fig.canvas.mpl_connect('draw_event', on_draw)
plt.show()
```
![自动调整子图](https://matplotlib.org/_images/sphx_glr_auto_subplots_adjust_0011.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.artist.Artist.get_window_extent
matplotlib.transforms.Bbox
matplotlib.transforms.Bbox.inverse_transformed
matplotlib.transforms.Bbox.union
matplotlib.figure.Figure.subplots_adjust
matplotlib.figure.SubplotParams
matplotlib.backend_bases.FigureCanvasBase.mpl_connect
```
## 下载这个示例
- [下载python源码: auto_subplots_adjust.py](https://matplotlib.org/_downloads/auto_subplots_adjust.py)
- [下载Jupyter notebook: auto_subplots_adjust.ipynb](https://matplotlib.org/_downloads/auto_subplots_adjust.ipynb)

View File

@@ -0,0 +1,108 @@
# Boxplot 演示
boxplot 的代码示例。
```python
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))
```
```python
fig1, ax1 = plt.subplots()
ax1.set_title('Basic Plot')
ax1.boxplot(data)
```
![Boxplot示例](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_001.png)
```python
fig2, ax2 = plt.subplots()
ax2.set_title('Notched boxes')
ax2.boxplot(data, notch=True)
```
![Boxplot示例2](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_002.png)
```python
green_diamond = dict(markerfacecolor='g', marker='D')
fig3, ax3 = plt.subplots()
ax3.set_title('Changed Outlier Symbols')
ax3.boxplot(data, flierprops=green_diamond)
```
![Boxplot示例3](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_003.png)
```python
fig4, ax4 = plt.subplots()
ax4.set_title('Hide Outlier Points')
ax4.boxplot(data, showfliers=False)
```
![Boxplot示例4](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_004.png)
```python
red_square = dict(markerfacecolor='r', marker='s')
fig5, ax5 = plt.subplots()
ax5.set_title('Horizontal Boxes')
ax5.boxplot(data, vert=False, flierprops=red_square)
```
![Boxplot示例5](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_005.png)
```python
fig6, ax6 = plt.subplots()
ax6.set_title('Shorter Whisker Length')
ax6.boxplot(data, flierprops=red_square, vert=False, whis=0.75)
```
![Boxplot示例6](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_006.png)
模拟一些更多的数据。
```python
spread = np.random.rand(50) * 100
center = np.ones(25) * 40
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
d2 = np.concatenate((spread, center, flier_high, flier_low))
data.shape = (-1, 1)
d2.shape = (-1, 1)
```
仅当所有列的长度相同时,才能生成二维数组。 如果不是,则使用列表。 这实际上更有效因为boxplot无论如何都会在内部将2-D数组转换为向量列表。
```python
data = [data, d2, d2[::2,0]]
fig7, ax7 = plt.subplots()
ax7.set_title('Multiple Samples with Different sizes')
ax7.boxplot(data)
plt.show()
```
![Boxplot示例7](https://matplotlib.org/_images/sphx_glr_boxplot_demo_pyplot_007.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.boxplot
matplotlib.pyplot.boxplot
```
## 下载这个示例
- [下载python源码: boxplot_demo_pyplot.py](https://matplotlib.org/_downloads/boxplot_demo_pyplot.py)
- [下载Jupyter notebook: boxplot_demo_pyplot.ipynb](https://matplotlib.org/_downloads/boxplot_demo_pyplot.ipynb)

View File

@@ -0,0 +1,45 @@
# 美元符刻度
使用 [FormatStrFormatter](https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FormatStrFormatter) 在y轴标签上添加美元符号。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
for tick in ax.yaxis.get_major_ticks():
tick.label1On = False
tick.label2On = True
tick.label2.set_color('green')
plt.show()
```
![美元符号刻度示例](https://matplotlib.org/_images/sphx_glr_dollar_ticks_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.ticker
matplotlib.ticker.FormatStrFormatter
matplotlib.axis.Axis.set_major_formatter
matplotlib.axis.Axis.get_major_ticks
matplotlib.axis.Tick
```
## 下载这个示例
- [下载python源码: dollar_ticks.py](https://matplotlib.org/_downloads/dollar_ticks.py)
- [下载Jupyter notebook: dollar_ticks.ipynb](https://matplotlib.org/_downloads/dollar_ticks.ipynb)

View File

@@ -0,0 +1,59 @@
# 简单的图轴自定义
自定义简单绘图的背景,标签和刻度。
```python
import matplotlib.pyplot as plt
```
用 ``plt.figure`` 创建一个 ``matplotlib.figure.Figure`` 实例
```python
fig = plt.figure()
rect = fig.patch # a rectangle instance
rect.set_facecolor('lightgoldenrodyellow')
ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])
rect = ax1.patch
rect.set_facecolor('lightslategray')
for label in ax1.xaxis.get_ticklabels():
# label is a Text instance
label.set_color('red')
label.set_rotation(45)
label.set_fontsize(16)
for line in ax1.yaxis.get_ticklines():
# line is a Line2D instance
line.set_color('green')
line.set_markersize(25)
line.set_markeredgewidth(3)
plt.show()
```
![简单的图轴自定义示例](https://matplotlib.org/_images/sphx_glr_fig_axes_customize_simple_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axis.Axis.get_ticklabels
matplotlib.axis.Axis.get_ticklines
matplotlib.text.Text.set_rotation
matplotlib.text.Text.set_fontsize
matplotlib.text.Text.set_color
matplotlib.lines.Line2D
matplotlib.lines.Line2D.set_color
matplotlib.lines.Line2D.set_markersize
matplotlib.lines.Line2D.set_markeredgewidth
matplotlib.patches.Patch.set_facecolor
```
## 下载这个示例
- [下载python源码: fig_axes_customize_simple.py](https://matplotlib.org/_downloads/fig_axes_customize_simple.py)
- [下载Jupyter notebook: fig_axes_customize_simple.ipynb](https://matplotlib.org/_downloads/fig_axes_customize_simple.ipynb)

View File

@@ -0,0 +1,50 @@
# 简单的图轴标记
标记图的轴。
```python
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(211)
ax1.set_ylabel('volts')
ax1.set_title('a sine wave')
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax1.plot(t, s, color='blue', lw=2)
# Fixing random state for reproducibility
np.random.seed(19680801)
ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
n, bins, patches = ax2.hist(np.random.randn(1000), 50,
facecolor='yellow', edgecolor='yellow')
ax2.set_xlabel('time (s)')
plt.show()
```
![简单的图轴标记示例](https://matplotlib.org/_images/sphx_glr_fig_axes_labels_simple_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.set_xlabel
matplotlib.axes.Axes.set_ylabel
matplotlib.axes.Axes.set_title
matplotlib.axes.Axes.plot
matplotlib.axes.Axes.hist
matplotlib.figure.Figure.add_axes
```
## 下载这个示例
- [下载python源码: fig_axes_labels_simple.py](https://matplotlib.org/_downloads/fig_axes_labels_simple.py)
- [下载Jupyter notebook: fig_axes_labels_simple.ipynb](https://matplotlib.org/_downloads/fig_axes_labels_simple.ipynb)

View File

@@ -0,0 +1,37 @@
# X图
添加线条到图形(没有轴)。
```python
import matplotlib.pyplot as plt
import matplotlib.lines as lines
fig = plt.figure()
l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig)
l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig)
fig.lines.extend([l1, l2])
plt.show()
```
![X图示例](https://matplotlib.org/_images/sphx_glr_fig_x_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.figure
matplotlib.lines
matplotlib.lines.Line2D
```
## 下载这个示例
- [下载python源码: fig_x.py](https://matplotlib.org/_downloads/fig_x.py)
- [下载Jupyter notebook: fig_x.ipynb](https://matplotlib.org/_downloads/fig_x.ipynb)

View File

@@ -0,0 +1,27 @@
# Pyplot 格式字符串(Formatstr)
使用格式字符串为绘图([plot](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot))着色并设置其标记。
```python
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
```
![格式字符串示例](https://matplotlib.org/_images/sphx_glr_pyplot_formatstr_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.plot
matplotlib.axes.Axes.plot
```
## 下载这个示例
- [下载python源码: pyplot_formatstr.py](https://matplotlib.org/_downloads/pyplot_formatstr.py)
- [下载Jupyter notebook: pyplot_formatstr.ipynb](https://matplotlib.org/_downloads/pyplot_formatstr.ipynb)

View File

@@ -0,0 +1,36 @@
# Pyplot 数学文本(Mathtext)
在文本标签中使用数学表达式。有关MathText的概述请参阅[编写数学表达式](https://matplotlib.org/tutorials/text/mathtext.html)。
```python
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()
```
![数学文本示例](https://matplotlib.org/_images/sphx_glr_pyplot_mathtext_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.text
matplotlib.axes.Axes.text
```
## 下载这个示例
- [下载python源码: pyplot_mathtext.py](https://matplotlib.org/_downloads/pyplot_mathtext.py)
- [下载Jupyter notebook: pyplot_mathtext.ipynb](https://matplotlib.org/_downloads/pyplot_mathtext.ipynb)

View File

@@ -0,0 +1,82 @@
# Pyplot 比例尺(Scales)
在不同的比例上创建图。这里显示了线性,对数,对称对数和对数标度。有关更多示例,请参阅库的[“缩放”](https://matplotlib.org/gallery/index.html#scales-examples)部分。
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter # useful for `logit` scale
# Fixing random state for reproducibility
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure(1)
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()
```
![Pyplot 比例尺示例](https://matplotlib.org/_images/sphx_glr_pyplot_scales_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.subplot
matplotlib.pyplot.subplots_adjust
matplotlib.pyplot.gca
matplotlib.pyplot.yscale
matplotlib.ticker.NullFormatter
matplotlib.axis.Axis.set_minor_formatter
```
## 下载这个示例
- [下载python源码: pyplot_scales.py](https://matplotlib.org/_downloads/pyplot_scales.py)
- [下载Jupyter notebook: pyplot_scales.ipynb](https://matplotlib.org/_downloads/pyplot_scales.ipynb)

View File

@@ -0,0 +1,28 @@
# Pyplot 简单图(Simple)
A most simple plot, where a list of numbers is plotted against their index.
```python
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
```
![简单图示例](https://matplotlib.org/_images/sphx_glr_pyplot_simple_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.plot
matplotlib.pyplot.ylabel
matplotlib.pyplot.show
```
## 下载这个示例
- [下载python源码: pyplot_simple.py](https://matplotlib.org/_downloads/pyplot_simple.py)
- [下载Jupyter notebook: pyplot_simple.ipynb](https://matplotlib.org/_downloads/pyplot_simple.ipynb)

View File

@@ -0,0 +1,45 @@
# Pyplot 文本(Text)
```python
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
```
![Pyplot 文本示例](https://matplotlib.org/_images/sphx_glr_pyplot_text_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.hist
matplotlib.pyplot.xlabel
matplotlib.pyplot.ylabel
matplotlib.pyplot.text
matplotlib.pyplot.grid
matplotlib.pyplot.show
```
## 下载这个示例
- [下载python源码: pyplot_text.py](https://matplotlib.org/_downloads/pyplot_text.py)
- [下载Jupyter notebook: pyplot_text.ipynb](https://matplotlib.org/_downloads/pyplot_text.ipynb)

View File

@@ -0,0 +1,32 @@
# Pyplot 绘制三条线
在一次调用 [plot](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) 绘图中绘制三个线图。
```python
import numpy as np
import matplotlib.pyplot as plt
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
```
![Pyplot 绘制三条线示例](https://matplotlib.org/_images/sphx_glr_pyplot_three_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.plot
matplotlib.axes.Axes.plot
```
## 下载这个示例
- [下载python源码: pyplot_three.py](https://matplotlib.org/_downloads/pyplot_three.py)
- [下载Jupyter notebook: pyplot_three.ipynb](https://matplotlib.org/_downloads/pyplot_three.ipynb)

View File

@@ -0,0 +1,39 @@
# Pyplot 绘制两个子图
使用pyplot.subplot创建带有两个子图的图形。
```python
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
```
![Pyplot 绘制两个子图示例](https://matplotlib.org/_images/sphx_glr_pyplot_two_subplots_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.pyplot.figure
matplotlib.pyplot.subplot
```
## 下载这个示例
- [下载python源码: pyplot_two_subplots.py](https://matplotlib.org/_downloads/pyplot_two_subplots.py)
- [下载Jupyter notebook: pyplot_two_subplots.ipynb](https://matplotlib.org/_downloads/pyplot_two_subplots.ipynb)

View File

@@ -0,0 +1,61 @@
# 绘制不同的文本
绘制许多不同种类的文本。
```python
import matplotlib.pyplot as plt
fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
ax.text(3, 2, 'unicode: Institut f\374r Festk\366rperphysik')
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.axis([0, 10, 0, 10])
plt.show()
```
![绘制不同的文本示例](https://matplotlib.org/_images/sphx_glr_text_commands_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.figure.Figure.suptitle
matplotlib.figure.Figure.add_subplot
matplotlib.figure.Figure.subplots_adjust
matplotlib.axes.Axes.set_title
matplotlib.axes.Axes.set_xlabel
matplotlib.axes.Axes.set_ylabel
matplotlib.axes.Axes.text
matplotlib.axes.Axes.annotate
```
## 下载这个示例
- [下载python源码: text_commands.py](https://matplotlib.org/_downloads/text_commands.py)
- [下载Jupyter notebook: text_commands.ipynb](https://matplotlib.org/_downloads/text_commands.ipynb)

View File

@@ -0,0 +1,100 @@
# 不同文本的布局
创建具有不同对齐和旋转的文本。
```python
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
# axes coordinates are 0,0 is bottom left and 1,1 is upper right
p = patches.Rectangle(
(left, bottom), width, height,
fill=False, transform=ax.transAxes, clip_on=False
)
ax.add_patch(p)
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5*(bottom+top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5*(bottom+top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
horizontalalignment='center',
verticalalignment='center',
fontsize=20, color='red',
transform=ax.transAxes)
ax.text(right, 0.5*(bottom+top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
ax.set_axis_off()
plt.show()
```
![不同文本的布局](https://matplotlib.org/_images/sphx_glr_text_layout_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.text
matplotlib.pyplot.text
```
## 下载这个示例
- [下载python源码: text_layout.py](https://matplotlib.org/_downloads/text_layout.py)
- [下载Jupyter notebook: text_layout.ipynb](https://matplotlib.org/_downloads/text_layout.ipynb)

View File

@@ -0,0 +1,57 @@
# 1.0版本新特性3d子图
在同一图中创建两个三维图。
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
from matplotlib import cm
#from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
linewidth=0, antialiased=False)
ax.set_zlim3d(-1.01, 1.01)
#ax.w_zaxis.set_major_locator(LinearLocator(10))
#ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.03f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
from mpl_toolkits.mplot3d.axes3d import get_test_data
ax = fig.add_subplot(1, 2, 2, projection='3d')
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
```
![3d子图示例](https://matplotlib.org/_images/sphx_glr_whats_new_1_subplot3d_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
import mpl_toolkits
matplotlib.figure.Figure.add_subplot
mpl_toolkits.mplot3d.axes3d.Axes3D.plot_surface
mpl_toolkits.mplot3d.axes3d.Axes3D.plot_wireframe
mpl_toolkits.mplot3d.axes3d.Axes3D.set_zlim3d
```
## 下载这个示例
- [下载python源码: whats_new_1_subplot3d.py](https://matplotlib.org/_downloads/whats_new_1_subplot3d.py)
- [下载Jupyter notebook: whats_new_1_subplot3d.ipynb](https://matplotlib.org/_downloads/whats_new_1_subplot3d.ipynb)

View File

@@ -0,0 +1,82 @@
# 0.98.4版本新的炫酷特性
创建精美的盒子和箭头样式。
```python
import matplotlib.patches as mpatch
import matplotlib.pyplot as plt
figheight = 8
fig = plt.figure(1, figsize=(9, figheight), dpi=80)
fontsize = 0.4 * fig.dpi
def make_boxstyles(ax):
styles = mpatch.BoxStyle.get_styles()
for i, (stylename, styleclass) in enumerate(sorted(styles.items())):
ax.text(0.5, (float(len(styles)) - 0.5 - i)/len(styles), stylename,
ha="center",
size=fontsize,
transform=ax.transAxes,
bbox=dict(boxstyle=stylename, fc="w", ec="k"))
def make_arrowstyles(ax):
styles = mpatch.ArrowStyle.get_styles()
ax.set_xlim(0, 4)
ax.set_ylim(0, figheight)
for i, (stylename, styleclass) in enumerate(sorted(styles.items())):
y = (float(len(styles)) -0.25 - i) # /figheight
p = mpatch.Circle((3.2, y), 0.2, fc="w")
ax.add_patch(p)
ax.annotate(stylename, (3.2, y),
(2., y),
#xycoords="figure fraction", textcoords="figure fraction",
ha="right", va="center",
size=fontsize,
arrowprops=dict(arrowstyle=stylename,
patchB=p,
shrinkA=5,
shrinkB=5,
fc="w", ec="k",
connectionstyle="arc3,rad=-0.05",
),
bbox=dict(boxstyle="square", fc="w"))
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax1 = fig.add_subplot(121, frameon=False, xticks=[], yticks=[])
make_boxstyles(ax1)
ax2 = fig.add_subplot(122, frameon=False, xticks=[], yticks=[])
make_arrowstyles(ax2)
plt.show()
```
![新特性示例](https://matplotlib.org/_images/sphx_glr_whats_new_98_4_fancy_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.patches
matplotlib.patches.BoxStyle
matplotlib.patches.BoxStyle.get_styles
matplotlib.patches.ArrowStyle
matplotlib.patches.ArrowStyle.get_styles
matplotlib.axes.Axes.text
matplotlib.axes.Axes.annotate
```
## 下载这个示例
- [下载python源码: whats_new_98_4_fancy.py](https://matplotlib.org/_downloads/whats_new_98_4_fancy.py)
- [下载Jupyter notebook: whats_new_98_4_fancy.ipynb](https://matplotlib.org/_downloads/whats_new_98_4_fancy.ipynb)

View File

@@ -0,0 +1,36 @@
# 填充交叉区域
填充两条曲线之间的区域。
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.01)
y1 = -5*x*x + x + 10
y2 = 5*x*x + x
fig, ax = plt.subplots()
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=y2 >y1, facecolor='yellow', alpha=0.5)
ax.fill_between(x, y1, y2, where=y2 <=y1, facecolor='red', alpha=0.5)
ax.set_title('Fill Between')
plt.show()
```
![填充示例](https://matplotlib.org/_images/sphx_glr_whats_new_98_4_fill_between_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.fill_between
```
## 下载这个示例
- [下载python源码: whats_new_98_4_fill_between.py](https://matplotlib.org/_downloads/whats_new_98_4_fill_between.py)
- [下载Jupyter notebook: whats_new_98_4_fill_between.ipynb](https://matplotlib.org/_downloads/whats_new_98_4_fill_between.ipynb)

View File

@@ -0,0 +1,39 @@
# 0.98.4版本图例新特性
创建图例并使用阴影和长方体对其进行调整。
```python
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111)
t1 = np.arange(0.0, 1.0, 0.01)
for n in [1, 2, 3, 4]:
plt.plot(t1, t1**n, label="n=%d"%(n,))
leg = plt.legend(loc='best', ncol=2, mode="expand", shadow=True, fancybox=True)
leg.get_frame().set_alpha(0.5)
plt.show()
```
![新特性图例示例](https://matplotlib.org/_images/sphx_glr_whats_new_98_4_legend_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.legend
matplotlib.pyplot.legend
matplotlib.legend.Legend
matplotlib.legend.Legend.get_frame
```
## 下载这个示例
- [下载python源码: whats_new_98_4_legend.py](https://matplotlib.org/_downloads/whats_new_98_4_legend.py)
- [下载Jupyter notebook: whats_new_98_4_legend.ipynb](https://matplotlib.org/_downloads/whats_new_98_4_legend.ipynb)

View File

@@ -0,0 +1,67 @@
# 0.99版本轴网格新特性
创建RGB合成图像。
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes
def get_demo_image():
# prepare image
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
return Z, extent
def get_rgb():
Z, extent = get_demo_image()
Z[Z < 0] = 0.
Z = Z / Z.max()
R = Z[:13, :13]
G = Z[2:, 2:]
B = Z[:13, 2:]
return R, G, B
fig = plt.figure(1)
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8])
r, g, b = get_rgb()
kwargs = dict(origin="lower", interpolation="nearest")
ax.imshow_rgb(r, g, b, **kwargs)
ax.RGB.set_xlim(0., 9.5)
ax.RGB.set_ylim(0.9, 10.6)
plt.show()
```
![创建RGB合成图像示例](https://matplotlib.org/_images/sphx_glr_whats_new_99_axes_grid_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import mpl_toolkits
mpl_toolkits.axes_grid1.axes_rgb.RGBAxes
mpl_toolkits.axes_grid1.axes_rgb.RGBAxes.imshow_rgb
```
## 下载这个示例
- [下载python源码: whats_new_99_axes_grid.py](https://matplotlib.org/_downloads/whats_new_99_axes_grid.py)
- [下载Jupyter notebook: whats_new_99_axes_grid.ipynb](https://matplotlib.org/_downloads/whats_new_99_axes_grid.ipynb)

View File

@@ -0,0 +1,39 @@
# 0.99版本新增Mplot3d对象
创建3D曲面图。
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)
plt.show()
```
![3D曲面图示例](https://matplotlib.org/_images/sphx_glr_whats_new_99_mplot3d_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import mpl_toolkits
mpl_toolkits.mplot3d.Axes3D
mpl_toolkits.mplot3d.Axes3D.plot_surface
```
## 下载这个示例
- [下载python源码: whats_new_99_mplot3d.py](https://matplotlib.org/_downloads/whats_new_99_mplot3d.py)
- [下载Jupyter notebook: whats_new_99_mplot3d.ipynb](https://matplotlib.org/_downloads/whats_new_99_mplot3d.ipynb)

View File

@@ -0,0 +1,72 @@
# 0.99版本新增Spines对象
```python
import matplotlib.pyplot as plt
import numpy as np
def adjust_spines(ax,spines):
for loc, spine in ax.spines.items():
if loc in spines:
spine.set_position(('outward',10)) # outward by 10 points
else:
spine.set_color('none') # don't draw spine
# turn off ticks where there is no spine
if 'left' in spines:
ax.yaxis.set_ticks_position('left')
else:
# no yaxis ticks
ax.yaxis.set_ticks([])
if 'bottom' in spines:
ax.xaxis.set_ticks_position('bottom')
else:
# no xaxis ticks
ax.xaxis.set_ticks([])
fig = plt.figure()
x = np.linspace(0,2*np.pi,100)
y = 2*np.sin(x)
ax = fig.add_subplot(2,2,1)
ax.plot(x,y)
adjust_spines(ax,['left'])
ax = fig.add_subplot(2,2,2)
ax.plot(x,y)
adjust_spines(ax,[])
ax = fig.add_subplot(2,2,3)
ax.plot(x,y)
adjust_spines(ax,['left','bottom'])
ax = fig.add_subplot(2,2,4)
ax.plot(x,y)
adjust_spines(ax,['bottom'])
plt.show()
```
![Spines对象绘图示例](https://matplotlib.org/_images/sphx_glr_whats_new_99_spines_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.axis.Axis.set_ticks
matplotlib.axis.XAxis.set_ticks_position
matplotlib.axis.YAxis.set_ticks_position
matplotlib.spines
matplotlib.spines.Spine
matplotlib.spines.Spine.set_color
matplotlib.spines.Spine.set_position
```
## 下载这个示例
- [下载python源码: whats_new_99_spines.py](https://matplotlib.org/_downloads/whats_new_99_spines.py)
- [下载Jupyter notebook: whats_new_99_spines.ipynb](https://matplotlib.org/_downloads/whats_new_99_spines.ipynb)