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,31 @@
# 双对数
![双对数示例](https://matplotlib.org/_images/sphx_glr_aspect_loglog_001.png)
```python
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_xscale("log")
ax1.set_yscale("log")
ax1.set_xlim(1e1, 1e3)
ax1.set_ylim(1e2, 1e3)
ax1.set_aspect(1)
ax1.set_title("adjustable = box")
ax2.set_xscale("log")
ax2.set_yscale("log")
ax2.set_adjustable("datalim")
ax2.plot([1, 3, 10], [1, 9, 100], "o-")
ax2.set_xlim(1e-1, 1e2)
ax2.set_ylim(1e-1, 1e3)
ax2.set_aspect(1)
ax2.set_title("adjustable = datalim")
plt.show()
```
## 下载这个示例
- [下载python源码: aspect_loglog.py](https://matplotlib.org/_downloads/aspect_loglog.py)
- [下载Jupyter notebook: aspect_loglog.ipynb](https://matplotlib.org/_downloads/aspect_loglog.ipynb)

View File

@@ -0,0 +1,187 @@
# 自定义比例尺
通过在墨卡托投影中实现纬度数据的缩放用途来创建自定义比例。
![自定义比例尺示例](https://matplotlib.org/_images/sphx_glr_custom_scale_001.png)
```python
import numpy as np
from numpy import ma
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from matplotlib.ticker import Formatter, FixedLocator
from matplotlib import rcParams
# BUG: this example fails with any other setting of axisbelow
rcParams['axes.axisbelow'] = False
class MercatorLatitudeScale(mscale.ScaleBase):
"""
Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using
the system used to scale latitudes in a Mercator projection.
The scale function:
ln(tan(y) + sec(y))
The inverse scale function:
atan(sinh(y))
Since the Mercator scale tends to infinity at +/- 90 degrees,
there is user-defined threshold, above and below which nothing
will be plotted. This defaults to +/- 85 degrees.
source:
http://en.wikipedia.org/wiki/Mercator_projection
"""
# The scale class must have a member ``name`` that defines the
# string used to select the scale. For example,
# ``gca().set_yscale("mercator")`` would be used to select this
# scale.
name = 'mercator'
def __init__(self, axis, *, thresh=np.deg2rad(85), **kwargs):
"""
Any keyword arguments passed to ``set_xscale`` and
``set_yscale`` will be passed along to the scale's
constructor.
thresh: The degree above which to crop the data.
"""
mscale.ScaleBase.__init__(self)
if thresh >= np.pi / 2:
raise ValueError("thresh must be less than pi/2")
self.thresh = thresh
def get_transform(self):
"""
Override this method to return a new instance that does the
actual transformation of the data.
The MercatorLatitudeTransform class is defined below as a
nested class of this one.
"""
return self.MercatorLatitudeTransform(self.thresh)
def set_default_locators_and_formatters(self, axis):
"""
Override to set up the locators and formatters to use with the
scale. This is only required if the scale requires custom
locators and formatters. Writing custom locators and
formatters is rather outside the scope of this example, but
there are many helpful examples in ``ticker.py``.
In our case, the Mercator example uses a fixed locator from
-90 to 90 degrees and a custom formatter class to put convert
the radians to degrees and put a degree symbol after the
value::
"""
class DegreeFormatter(Formatter):
def __call__(self, x, pos=None):
return "%d\N{DEGREE SIGN}" % np.degrees(x)
axis.set_major_locator(FixedLocator(
np.radians(np.arange(-90, 90, 10))))
axis.set_major_formatter(DegreeFormatter())
axis.set_minor_formatter(DegreeFormatter())
def limit_range_for_scale(self, vmin, vmax, minpos):
"""
Override to limit the bounds of the axis to the domain of the
transform. In the case of Mercator, the bounds should be
limited to the threshold that was passed in. Unlike the
autoscaling provided by the tick locators, this range limiting
will always be adhered to, whether the axis range is set
manually, determined automatically or changed through panning
and zooming.
"""
return max(vmin, -self.thresh), min(vmax, self.thresh)
class MercatorLatitudeTransform(mtransforms.Transform):
# There are two value members that must be defined.
# ``input_dims`` and ``output_dims`` specify number of input
# dimensions and output dimensions to the transformation.
# These are used by the transformation framework to do some
# error checking and prevent incompatible transformations from
# being connected together. When defining transforms for a
# scale, which are, by definition, separable and have only one
# dimension, these members should always be set to 1.
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
"""
This transform takes an Nx1 ``numpy`` array and returns a
transformed copy. Since the range of the Mercator scale
is limited by the user-specified threshold, the input
array must be masked to contain only valid values.
``matplotlib`` will handle masked arrays and remove the
out-of-range data from the plot. Importantly, the
``transform`` method *must* return an array that is the
same shape as the input array, since these values need to
remain synchronized with values in the other dimension.
"""
masked = ma.masked_where((a < -self.thresh) | (a > self.thresh), a)
if masked.mask.any():
return ma.log(np.abs(ma.tan(masked) + 1.0 / ma.cos(masked)))
else:
return np.log(np.abs(np.tan(a) + 1.0 / np.cos(a)))
def inverted(self):
"""
Override this method so matplotlib knows how to get the
inverse transform for this transform.
"""
return MercatorLatitudeScale.InvertedMercatorLatitudeTransform(
self.thresh)
class InvertedMercatorLatitudeTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
return np.arctan(np.sinh(a))
def inverted(self):
return MercatorLatitudeScale.MercatorLatitudeTransform(self.thresh)
# Now that the Scale class has been defined, it must be registered so
# that ``matplotlib`` can find it.
mscale.register_scale(MercatorLatitudeScale)
if __name__ == '__main__':
import matplotlib.pyplot as plt
t = np.arange(-180.0, 180.0, 0.1)
s = np.radians(t)/2.
plt.plot(t, s, '-', lw=2)
plt.gca().set_yscale('mercator')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('Mercator: Projection of the Oppressor')
plt.grid(True)
plt.show()
```
## 下载这个示例
- [下载python源码: custom_scale.py](https://matplotlib.org/_downloads/custom_scale.py)
- [下载Jupyter notebook: custom_scale.ipynb](https://matplotlib.org/_downloads/custom_scale.ipynb)

View File

@@ -0,0 +1,3 @@
# 刻度、比例尺
这些示例介绍了如何在Matplotlib中处理不同的比例。

View File

@@ -0,0 +1,35 @@
# 对数条形图
绘制具有对数y轴的条形图。
![对数条形图示例](https://matplotlib.org/_images/sphx_glr_log_bar_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
data = ((3, 1000), (10, 3), (100, 30), (500, 800), (50, 1))
dim = len(data[0])
w = 0.75
dimw = w / dim
fig, ax = plt.subplots()
x = np.arange(len(data))
for i in range(len(data[0])):
y = [d[i] for d in data]
b = ax.bar(x + i * dimw, y, dimw, bottom=0.001)
ax.set_xticks(x + dimw / 2, map(str, x))
ax.set_yscale('log')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
```
## 下载这个示例
- [下载python源码: log_bar.py](https://matplotlib.org/_downloads/log_bar.py)
- [下载Jupyter notebook: log_bar.ipynb](https://matplotlib.org/_downloads/log_bar.ipynb)

View File

@@ -0,0 +1,51 @@
# 对数演示
具有对数轴的图的示例。
![对数演示](https://matplotlib.org/_images/sphx_glr_log_demo_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
# Data for plotting
t = np.arange(0.01, 20.0, 0.01)
# Create figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
# log y axis
ax1.semilogy(t, np.exp(-t / 5.0))
ax1.set(title='semilogy')
ax1.grid()
# log x axis
ax2.semilogx(t, np.sin(2 * np.pi * t))
ax2.set(title='semilogx')
ax2.grid()
# log x and y axis
ax3.loglog(t, 20 * np.exp(-t / 10.0), basex=2)
ax3.set(title='loglog base 2 on x')
ax3.grid()
# With errorbars: clip non-positive values
# Use new data for plotting
x = 10.0**np.linspace(0.0, 2.0, 20)
y = x**2.0
ax4.set_xscale("log", nonposx='clip')
ax4.set_yscale("log", nonposy='clip')
ax4.set(title='Errorbars go negative')
ax4.errorbar(x, y, xerr=0.1 * x, yerr=5.0 + 0.75 * y)
# ylim must be set after errorbar to allow errorbar to autoscale limits
ax4.set_ylim(bottom=0.1)
fig.tight_layout()
plt.show()
```
## 下载这个示例
- [下载python源码: log_demo.py](https://matplotlib.org/_downloads/log_demo.py)
- [下载Jupyter notebook: log_demo.ipynb](https://matplotlib.org/_downloads/log_demo.ipynb)

View File

@@ -0,0 +1,25 @@
# 对数轴
这是使用semilogx为x轴分配对数刻度的示例。
![对数轴示例](https://matplotlib.org/_images/sphx_glr_log_test_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
dt = 0.01
t = np.arange(dt, 20.0, dt)
ax.semilogx(t, np.exp(-t / 5.0))
ax.grid()
plt.show()
```
## 下载这个示例
- [下载python源码: log_test.py](https://matplotlib.org/_downloads/log_test.py)
- [下载Jupyter notebook: log_test.ipynb](https://matplotlib.org/_downloads/log_test.ipynb)

View File

@@ -0,0 +1,50 @@
# 探索规范化
多元正态分布的各种归一化。
```python
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from numpy.random import multivariate_normal
data = np.vstack([
multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
])
gammas = [0.8, 0.5, 0.3]
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 0].set_title('Linear normalization')
axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)
for ax, gamma in zip(axes.flat[1:], gammas):
ax.set_title(r'Power law $(\gamma=%1.1f)$' % gamma)
ax.hist2d(data[:, 0], data[:, 1],
bins=100, norm=mcolors.PowerNorm(gamma))
fig.tight_layout()
plt.show()
```
![探索规范化示例](https://matplotlib.org/_images/sphx_glr_power_norm_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.colors
matplotlib.colors.PowerNorm
matplotlib.axes.Axes.hist2d
matplotlib.pyplot.hist2d
```
## 下载这个示例
- [下载python源码: power_norm.py](https://matplotlib.org/_downloads/power_norm.py)
- [下载Jupyter notebook: power_norm.ipynb](https://matplotlib.org/_downloads/power_norm.ipynb)

View File

@@ -0,0 +1,63 @@
# 比例尺
说明应用于轴的比例变换,例如: logsymloglogit。
![比例尺示例](https://matplotlib.org/_images/sphx_glr_scales_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
# 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
fig, axs = plt.subplots(2, 2, sharex=True)
fig.subplots_adjust(left=0.08, right=0.98, wspace=0.3)
# linear
ax = axs[0, 0]
ax.plot(x, y)
ax.set_yscale('linear')
ax.set_title('linear')
ax.grid(True)
# log
ax = axs[0, 1]
ax.plot(x, y)
ax.set_yscale('log')
ax.set_title('log')
ax.grid(True)
# symmetric log
ax = axs[1, 1]
ax.plot(x, y - y.mean())
ax.set_yscale('symlog', linthreshy=0.02)
ax.set_title('symlog')
ax.grid(True)
# logit
ax = axs[1, 0]
ax.plot(x, y)
ax.set_yscale('logit')
ax.set_title('logit')
ax.grid(True)
ax.yaxis.set_minor_formatter(NullFormatter())
plt.show()
```
## 下载这个示例
- [下载python源码: scales.py](https://matplotlib.org/_downloads/scales.py)
- [下载Jupyter notebook: scales.ipynb](https://matplotlib.org/_downloads/scales.ipynb)

View File

@@ -0,0 +1,41 @@
# Symlog演示
示例使用symlog对称对数轴缩放。
![Symlog演示](https://matplotlib.org/_images/sphx_glr_symlog_demo_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
dt = 0.01
x = np.arange(-50.0, 50.0, dt)
y = np.arange(0, 100.0, dt)
plt.subplot(311)
plt.plot(x, y)
plt.xscale('symlog')
plt.ylabel('symlogx')
plt.grid(True)
plt.gca().xaxis.grid(True, which='minor') # minor grid on too
plt.subplot(312)
plt.plot(y, x)
plt.yscale('symlog')
plt.ylabel('symlogy')
plt.subplot(313)
plt.plot(x, np.sin(x / 3.0))
plt.xscale('symlog')
plt.yscale('symlog', linthreshy=0.015)
plt.grid(True)
plt.ylabel('symlog both')
plt.tight_layout()
plt.show()
```
## 下载这个示例
- [下载python源码: symlog_demo.py](https://matplotlib.org/_downloads/symlog_demo.py)
- [下载Jupyter notebook: symlog_demo.ipynb](https://matplotlib.org/_downloads/symlog_demo.ipynb)