mirror of
https://github.com/Estom/notes.git
synced 2026-11-27 22:01:41 +08:00
matplotlib & pandas
This commit is contained in:
59
Python/matplotlab/gallery/ticks_and_spines/auto_ticks.md
Normal file
59
Python/matplotlab/gallery/ticks_and_spines/auto_ticks.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# 自动设置记号标签
|
||||
|
||||
设置刻度自动放置的行为。
|
||||
|
||||
如果您没有明确设置刻度位置/标签,Matplotlib将尝试根据显示的数据及其限制自动选择它们。
|
||||
|
||||
默认情况下,这会尝试选择沿轴分布的刻度位置:
|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
np.random.seed(19680801)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
dots = np.arange(10) / 100. + .03
|
||||
x, y = np.meshgrid(dots, dots)
|
||||
data = [x.ravel(), y.ravel()]
|
||||
ax.scatter(*data, c=data[1])
|
||||
```
|
||||
|
||||

|
||||
|
||||
有时选择均匀分布的刻度会产生奇怪的刻度数。 如果您希望Matplotlib保持位于圆形数字的刻度线,则可以使用以下rcParams值更改此行为:
|
||||
|
||||
```python
|
||||
print(plt.rcParams['axes.autolimit_mode'])
|
||||
|
||||
# Now change this value and see the results
|
||||
with plt.rc_context({'axes.autolimit_mode': 'round_numbers'}):
|
||||
fig, ax = plt.subplots()
|
||||
ax.scatter(*data, c=data[1])
|
||||
```
|
||||
|
||||

|
||||
|
||||
输出:
|
||||
|
||||
```python
|
||||
data
|
||||
```
|
||||
|
||||
您还可以通过轴改变数据周围轴的边距。(x,y)边距:
|
||||
|
||||
```python
|
||||
with plt.rc_context({'axes.autolimit_mode': 'round_numbers',
|
||||
'axes.xmargin': .8,
|
||||
'axes.ymargin': .8}):
|
||||
fig, ax = plt.subplots()
|
||||
ax.scatter(*data, c=data[1])
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: auto_ticks.py](https://matplotlib.org/_downloads/auto_ticks.py)
|
||||
- [下载Jupyter notebook: auto_ticks.ipynb](https://matplotlib.org/_downloads/auto_ticks.ipynb)
|
||||
@@ -0,0 +1,50 @@
|
||||
# 居中TickLabels
|
||||
|
||||
有时将ticklabels置于中心是件好事。 Matplotlib目前将标签与刻度线关联,标签可以使用水平对齐属性对齐“中心”,“左”或“右”:
|
||||
|
||||
```python
|
||||
ax.xaxis.set_tick_params(horizontalalignment='right')
|
||||
```
|
||||
|
||||
但这并没有帮助将标签置于刻度之间。一种解决方案是“伪造它”。 使用次要刻度在主要刻度之间放置一个刻度。这是一个标记月份的示例,以ticks为中心。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.cbook as cbook
|
||||
import matplotlib.dates as dates
|
||||
import matplotlib.ticker as ticker
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# load some financial data; apple's stock price
|
||||
with cbook.get_sample_data('aapl.npz') as fh:
|
||||
r = np.load(fh)['price_data'].view(np.recarray)
|
||||
r = r[-250:] # get the last 250 days
|
||||
# Matplotlib works better with datetime.datetime than np.datetime64, but the
|
||||
# latter is more portable.
|
||||
date = r.date.astype('O')
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot(date, r.adj_close)
|
||||
|
||||
ax.xaxis.set_major_locator(dates.MonthLocator())
|
||||
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15))
|
||||
|
||||
ax.xaxis.set_major_formatter(ticker.NullFormatter())
|
||||
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
|
||||
|
||||
for tick in ax.xaxis.get_minor_ticks():
|
||||
tick.tick1line.set_markersize(0)
|
||||
tick.tick2line.set_markersize(0)
|
||||
tick.label1.set_horizontalalignment('center')
|
||||
|
||||
imid = len(r) // 2
|
||||
ax.set_xlabel(str(date[imid].year))
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: centered_ticklabels.py](https://matplotlib.org/_downloads/centered_ticklabels.py)
|
||||
- [下载Jupyter notebook: centered_ticklabels.ipynb](https://matplotlib.org/_downloads/centered_ticklabels.ipynb)
|
||||
@@ -0,0 +1,52 @@
|
||||
# 颜色栏刻度标签演示
|
||||
|
||||
为彩条生成自定义标签。
|
||||
|
||||
供稿人:Scott Sinclair
|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from matplotlib import cm
|
||||
from numpy.random import randn
|
||||
```
|
||||
|
||||
使用垂直(默认)颜色条创建绘图
|
||||
|
||||
```python
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
data = np.clip(randn(250, 250), -1, 1)
|
||||
|
||||
cax = ax.imshow(data, interpolation='nearest', cmap=cm.coolwarm)
|
||||
ax.set_title('Gaussian noise with vertical colorbar')
|
||||
|
||||
# Add colorbar, make sure to specify tick locations to match desired ticklabels
|
||||
cbar = fig.colorbar(cax, ticks=[-1, 0, 1])
|
||||
cbar.ax.set_yticklabels(['< -1', '0', '> 1']) # vertically oriented colorbar
|
||||
```
|
||||
|
||||

|
||||
|
||||
使用水平颜色条制作绘图
|
||||
|
||||
```python
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
data = np.clip(randn(250, 250), -1, 1)
|
||||
|
||||
cax = ax.imshow(data, interpolation='nearest', cmap=cm.afmhot)
|
||||
ax.set_title('Gaussian noise with horizontal colorbar')
|
||||
|
||||
cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal')
|
||||
cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) # horizontal colorbar
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: colorbar_tick_labelling_demo.py](https://matplotlib.org/_downloads/colorbar_tick_labelling_demo.py)
|
||||
- [下载Jupyter notebook: colorbar_tick_labelling_demo.ipynb](https://matplotlib.org/_downloads/colorbar_tick_labelling_demo.ipynb)
|
||||
35
Python/matplotlab/gallery/ticks_and_spines/custom_ticker1.md
Normal file
35
Python/matplotlab/gallery/ticks_and_spines/custom_ticker1.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# 自定义Ticker1
|
||||
|
||||
新的自动收报机代码旨在明确支持用户自定义滴答。[matplotlib.ticker](https://matplotlib.org/api/ticker_api.html#module-matplotlib.ticker) 的文档详细介绍了此过程。 该代码定义了许多预设代码,但主要设计为用户可扩展。
|
||||
|
||||
在此示例中,用户定义的函数用于格式化y轴上数百万美元的刻度。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
from matplotlib.ticker import FuncFormatter
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
x = np.arange(4)
|
||||
money = [1.5e5, 2.5e6, 5.5e6, 2.0e7]
|
||||
|
||||
|
||||
def millions(x, pos):
|
||||
'The two args are the value and tick position'
|
||||
return '$%1.1fM' % (x * 1e-6)
|
||||
|
||||
|
||||
formatter = FuncFormatter(millions)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.yaxis.set_major_formatter(formatter)
|
||||
plt.bar(x, money)
|
||||
plt.xticks(x, ('Bill', 'Fred', 'Mary', 'Sue'))
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: custom_ticker1.py](https://matplotlib.org/_downloads/custom_ticker1.py)
|
||||
- [下载Jupyter notebook: custom_ticker1.ipynb](https://matplotlib.org/_downloads/custom_ticker1.ipynb)
|
||||
@@ -0,0 +1,42 @@
|
||||
# 演示日期转换
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import datetime
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
|
||||
import numpy as np
|
||||
|
||||
date1 = datetime.datetime(2000, 3, 2)
|
||||
date2 = datetime.datetime(2000, 3, 6)
|
||||
delta = datetime.timedelta(hours=6)
|
||||
dates = drange(date1, date2, delta)
|
||||
|
||||
y = np.arange(len(dates))
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot_date(dates, y ** 2)
|
||||
|
||||
# this is superfluous, since the autoscaler should get it right, but
|
||||
# use date2num and num2date to convert between dates and floats if
|
||||
# you want; both date2num and num2date convert an instance or sequence
|
||||
ax.set_xlim(dates[0], dates[-1])
|
||||
|
||||
# The hour locator takes the hour or sequence of hours you want to
|
||||
# tick, not the base multiple
|
||||
|
||||
ax.xaxis.set_major_locator(DayLocator())
|
||||
ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))
|
||||
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
|
||||
|
||||
ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')
|
||||
fig.autofmt_xdate()
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: date_demo_convert.py](https://matplotlib.org/_downloads/date_demo_convert.py)
|
||||
- [下载Jupyter notebook: date_demo_convert.ipynb](https://matplotlib.org/_downloads/date_demo_convert.ipynb)
|
||||
@@ -0,0 +1,44 @@
|
||||
# 演示日期Rrule
|
||||
|
||||
展示如何使用Rrule实例制作自定义日期自动收报机 - 这里我们在每5个复活节放置一个刻度线。
|
||||
|
||||
有关Rrules的帮助,请参阅https://dateutil.readthedocs.io/en/stable/
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.dates import (YEARLY, DateFormatter,
|
||||
rrulewrapper, RRuleLocator, drange)
|
||||
import numpy as np
|
||||
import datetime
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
|
||||
# tick every 5th easter
|
||||
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
|
||||
loc = RRuleLocator(rule)
|
||||
formatter = DateFormatter('%m/%d/%y')
|
||||
date1 = datetime.date(1952, 1, 1)
|
||||
date2 = datetime.date(2004, 4, 12)
|
||||
delta = datetime.timedelta(days=100)
|
||||
|
||||
dates = drange(date1, date2, delta)
|
||||
s = np.random.rand(len(dates)) # make up some random y values
|
||||
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
plt.plot_date(dates, s)
|
||||
ax.xaxis.set_major_locator(loc)
|
||||
ax.xaxis.set_major_formatter(formatter)
|
||||
ax.xaxis.set_tick_params(rotation=30, labelsize=10)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: date_demo_rrule.py](https://matplotlib.org/_downloads/date_demo_rrule.py)
|
||||
- [下载Jupyter notebook: date_demo_rrule.ipynb](https://matplotlib.org/_downloads/date_demo_rrule.ipynb)
|
||||
@@ -0,0 +1,53 @@
|
||||
# 日期索引格式化程序
|
||||
|
||||
在绘制每日数据时,频繁的请求是绘制忽略跳过的数据,例如,周末没有额外的空格。这在金融时间序列中尤为常见,因为您可能拥有M-F而非Sat,Sun的数据,并且您不需要x轴上的间隙。方法是简单地使用xdata的整数索引和自定义刻度Formatter来获取给定索引的适当日期字符串。
|
||||
|
||||

|
||||
|
||||
输出:
|
||||
|
||||
```python
|
||||
loading /home/tcaswell/mc3/envs/dd37/lib/python3.7/site-packages/matplotlib/mpl-data/sample_data/msft.csv
|
||||
```
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.cbook as cbook
|
||||
from matplotlib.dates import bytespdate2num, num2date
|
||||
from matplotlib.ticker import Formatter
|
||||
|
||||
|
||||
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
|
||||
print('loading %s' % datafile)
|
||||
msft_data = np.genfromtxt(datafile, delimiter=',', names=True,
|
||||
converters={0: bytespdate2num('%d-%b-%y')})[-40:]
|
||||
|
||||
|
||||
class MyFormatter(Formatter):
|
||||
def __init__(self, dates, fmt='%Y-%m-%d'):
|
||||
self.dates = dates
|
||||
self.fmt = fmt
|
||||
|
||||
def __call__(self, x, pos=0):
|
||||
'Return the label for time x at position pos'
|
||||
ind = int(np.round(x))
|
||||
if ind >= len(self.dates) or ind < 0:
|
||||
return ''
|
||||
|
||||
return num2date(self.dates[ind]).strftime(self.fmt)
|
||||
|
||||
formatter = MyFormatter(msft_data['Date'])
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.xaxis.set_major_formatter(formatter)
|
||||
ax.plot(np.arange(len(msft_data)), msft_data['Close'], 'o-')
|
||||
fig.autofmt_xdate()
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: date_index_formatter2.py](https://matplotlib.org/_downloads/date_index_formatter2.py)
|
||||
- [下载Jupyter notebook: date_index_formatter2.ipynb](https://matplotlib.org/_downloads/date_index_formatter2.ipynb)
|
||||
@@ -0,0 +1,79 @@
|
||||
# Major和Minor的演示
|
||||
|
||||
演示如何使用Major和Minor代码。
|
||||
|
||||
两个相关的用户空类是Locators和Formatters。定位器确定刻度的位置,格式化程序控制刻度的格式。
|
||||
|
||||
默认情况下,小刻度线是关闭的(NullLocator和NullFormatter)。您可以通过设置次要定位器来转换w / o标签上的次要刻度。您还可以通过设置次要格式化程序为次要股票代码打开标签
|
||||
|
||||
制作一个主刻度线为20的倍数和小刻度为5的倍数的图。标记主要刻度与%d格式但不标记次刻度。
|
||||
|
||||
MultipleLocator自动收报机类用于在一些基数的倍数上放置滴答。 FormatStrFormatter使用字符串格式字符串(例如,'%d'或'%1.2f'或'%1.1f cm')来格式化刻度线
|
||||
|
||||
pyplot interface grid命令一起更改y轴和y轴的主刻度线的网格设置。如果要控制给定轴的次刻度的网格,请使用例子中的方式。
|
||||
|
||||
```python
|
||||
ax.xaxis.grid(True, which='minor')
|
||||
```
|
||||
|
||||
请注意,您不应在不同的Axis之间使用相同的定位器,因为定位器存储对Axis数据和视图限制的引用。
|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
|
||||
AutoMinorLocator)
|
||||
|
||||
majorLocator = MultipleLocator(20)
|
||||
majorFormatter = FormatStrFormatter('%d')
|
||||
minorLocator = MultipleLocator(5)
|
||||
|
||||
|
||||
t = np.arange(0.0, 100.0, 0.1)
|
||||
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot(t, s)
|
||||
|
||||
ax.xaxis.set_major_locator(majorLocator)
|
||||
ax.xaxis.set_major_formatter(majorFormatter)
|
||||
|
||||
# for the minor ticks, use no labels; default NullFormatter
|
||||
ax.xaxis.set_minor_locator(minorLocator)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
主要和次要刻度的自动刻度选择。
|
||||
|
||||
使用交互式平移和缩放来查看滴答间隔如何变化。每个主要间隔将有4或5个次要滴答间隔,具体取决于主要间隔。
|
||||
|
||||
可以为AutoMinorLocator提供一个参数,以指定每个主要区间的固定数量的次要区间,例如:minorLocator = AutoMinorLocator(2) 将导致主要区间之间的单个小标记。
|
||||
|
||||
```python
|
||||
minorLocator = AutoMinorLocator()
|
||||
|
||||
|
||||
t = np.arange(0.0, 100.0, 0.01)
|
||||
s = np.sin(2 * np.pi * t) * np.exp(-t * 0.01)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot(t, s)
|
||||
|
||||
ax.xaxis.set_minor_locator(minorLocator)
|
||||
|
||||
ax.tick_params(which='both', width=2)
|
||||
ax.tick_params(which='major', length=7)
|
||||
ax.tick_params(which='minor', length=4, color='r')
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: major_minor_demo.py](https://matplotlib.org/_downloads/major_minor_demo.py)
|
||||
- [下载Jupyter notebook: major_minor_demo.ipynb](https://matplotlib.org/_downloads/major_minor_demo.ipynb)
|
||||
@@ -0,0 +1,70 @@
|
||||
# 多个Yaxis与Spines
|
||||
|
||||
使用共享x轴创建多个y轴。这是通过创建一个[双轴](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.twinx.html#matplotlib.axes.Axes.twinx),转动所有脊柱但右边的一个不可见并使用[set_position](https://matplotlib.org/api/spines_api.html#matplotlib.spines.Spine.set_position)偏移其位置来完成的。
|
||||
|
||||
请注意,此方法使用 [matplotlib.axes.Axes](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes) 及其Spines。 寄生虫轴的另一种方法显示在[Demo Parasite Axes](https://matplotlib.org/gallery/axisartist/demo_parasite_axes.html) 和 [Demo Parasite Axes2](https://matplotlib.org/gallery/axisartist/demo_parasite_axes2.html)示例中。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def make_patch_spines_invisible(ax):
|
||||
ax.set_frame_on(True)
|
||||
ax.patch.set_visible(False)
|
||||
for sp in ax.spines.values():
|
||||
sp.set_visible(False)
|
||||
|
||||
|
||||
fig, host = plt.subplots()
|
||||
fig.subplots_adjust(right=0.75)
|
||||
|
||||
par1 = host.twinx()
|
||||
par2 = host.twinx()
|
||||
|
||||
# Offset the right spine of par2. The ticks and label have already been
|
||||
# placed on the right by twinx above.
|
||||
par2.spines["right"].set_position(("axes", 1.2))
|
||||
# Having been created by twinx, par2 has its frame off, so the line of its
|
||||
# detached spine is invisible. First, activate the frame but make the patch
|
||||
# and spines invisible.
|
||||
make_patch_spines_invisible(par2)
|
||||
# Second, show the right spine.
|
||||
par2.spines["right"].set_visible(True)
|
||||
|
||||
p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
|
||||
p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
|
||||
p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-", label="Velocity")
|
||||
|
||||
host.set_xlim(0, 2)
|
||||
host.set_ylim(0, 2)
|
||||
par1.set_ylim(0, 4)
|
||||
par2.set_ylim(1, 65)
|
||||
|
||||
host.set_xlabel("Distance")
|
||||
host.set_ylabel("Density")
|
||||
par1.set_ylabel("Temperature")
|
||||
par2.set_ylabel("Velocity")
|
||||
|
||||
host.yaxis.label.set_color(p1.get_color())
|
||||
par1.yaxis.label.set_color(p2.get_color())
|
||||
par2.yaxis.label.set_color(p3.get_color())
|
||||
|
||||
tkw = dict(size=4, width=1.5)
|
||||
host.tick_params(axis='y', colors=p1.get_color(), **tkw)
|
||||
par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
|
||||
par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
|
||||
host.tick_params(axis='x', **tkw)
|
||||
|
||||
lines = [p1, p2, p3]
|
||||
|
||||
host.legend(lines, [l.get_label() for l in lines])
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: multiple_yaxis_with_spines.py](https://matplotlib.org/_downloads/multiple_yaxis_with_spines.py)
|
||||
- [下载Jupyter notebook: multiple_yaxis_with_spines.ipynb](https://matplotlib.org/_downloads/multiple_yaxis_with_spines.ipynb)
|
||||
113
Python/matplotlab/gallery/ticks_and_spines/scalarformatter.md
Normal file
113
Python/matplotlab/gallery/ticks_and_spines/scalarformatter.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# 使用ScalarFormat标记格式
|
||||
|
||||
该示例显示了ScalarFormatter与不同设置的使用。
|
||||
|
||||
例子1:默认
|
||||
|
||||
例子2:没有图形偏移
|
||||
|
||||
例子3:使用Mathtext
|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from matplotlib.ticker import ScalarFormatter
|
||||
```
|
||||
|
||||
例子1:
|
||||
|
||||
```python
|
||||
x = np.arange(0, 1, .01)
|
||||
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(6, 6))
|
||||
fig.text(0.5, 0.975, 'The new formatter, default settings',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='top')
|
||||
|
||||
ax1.plot(x * 1e5 + 1e10, x * 1e-10 + 1e-5)
|
||||
ax1.xaxis.set_major_formatter(ScalarFormatter())
|
||||
ax1.yaxis.set_major_formatter(ScalarFormatter())
|
||||
|
||||
ax2.plot(x * 1e5, x * 1e-4)
|
||||
ax2.xaxis.set_major_formatter(ScalarFormatter())
|
||||
ax2.yaxis.set_major_formatter(ScalarFormatter())
|
||||
|
||||
ax3.plot(-x * 1e5 - 1e10, -x * 1e-5 - 1e-10)
|
||||
ax3.xaxis.set_major_formatter(ScalarFormatter())
|
||||
ax3.yaxis.set_major_formatter(ScalarFormatter())
|
||||
|
||||
ax4.plot(-x * 1e5, -x * 1e-4)
|
||||
ax4.xaxis.set_major_formatter(ScalarFormatter())
|
||||
ax4.yaxis.set_major_formatter(ScalarFormatter())
|
||||
|
||||
fig.subplots_adjust(wspace=0.7, hspace=0.6)
|
||||
```
|
||||
|
||||

|
||||
|
||||
例子2:
|
||||
|
||||
```python
|
||||
x = np.arange(0, 1, .01)
|
||||
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(6, 6))
|
||||
fig.text(0.5, 0.975, 'The new formatter, no numerical offset',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='top')
|
||||
|
||||
ax1.plot(x * 1e5 + 1e10, x * 1e-10 + 1e-5)
|
||||
ax1.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
ax1.yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
|
||||
ax2.plot(x * 1e5, x * 1e-4)
|
||||
ax2.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
ax2.yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
|
||||
ax3.plot(-x * 1e5 - 1e10, -x * 1e-5 - 1e-10)
|
||||
ax3.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
ax3.yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
|
||||
ax4.plot(-x * 1e5, -x * 1e-4)
|
||||
ax4.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
ax4.yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
|
||||
|
||||
fig.subplots_adjust(wspace=0.7, hspace=0.6)
|
||||
```
|
||||
|
||||

|
||||
|
||||
例子3:
|
||||
|
||||
```python
|
||||
x = np.arange(0, 1, .01)
|
||||
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(6, 6))
|
||||
fig.text(0.5, 0.975, 'The new formatter, with mathtext',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='top')
|
||||
|
||||
ax1.plot(x * 1e5 + 1e10, x * 1e-10 + 1e-5)
|
||||
ax1.xaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
ax1.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
|
||||
ax2.plot(x * 1e5, x * 1e-4)
|
||||
ax2.xaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
ax2.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
|
||||
ax3.plot(-x * 1e5 - 1e10, -x * 1e-5 - 1e-10)
|
||||
ax3.xaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
ax3.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
|
||||
ax4.plot(-x * 1e5, -x * 1e-4)
|
||||
ax4.xaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
ax4.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
|
||||
|
||||
fig.subplots_adjust(wspace=0.7, hspace=0.6)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: scalarformatter.py](https://matplotlib.org/_downloads/scalarformatter.py)
|
||||
- [下载Jupyter notebook: scalarformatter.ipynb](https://matplotlib.org/_downloads/scalarformatter.ipynb)
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# Spine的放置演示
|
||||
|
||||
调整轴Spine的位置和外观。
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
```
|
||||
|
||||
```python
|
||||
fig = plt.figure()
|
||||
x = np.linspace(-np.pi, np.pi, 100)
|
||||
y = 2 * np.sin(x)
|
||||
|
||||
ax = fig.add_subplot(2, 2, 1)
|
||||
ax.set_title('centered spines')
|
||||
ax.plot(x, y)
|
||||
ax.spines['left'].set_position('center')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('center')
|
||||
ax.spines['top'].set_color('none')
|
||||
ax.spines['left'].set_smart_bounds(True)
|
||||
ax.spines['bottom'].set_smart_bounds(True)
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
|
||||
ax = fig.add_subplot(2, 2, 2)
|
||||
ax.set_title('zeroed spines')
|
||||
ax.plot(x, y)
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
ax.spines['left'].set_smart_bounds(True)
|
||||
ax.spines['bottom'].set_smart_bounds(True)
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
|
||||
ax = fig.add_subplot(2, 2, 3)
|
||||
ax.set_title('spines at axes (0.6, 0.1)')
|
||||
ax.plot(x, y)
|
||||
ax.spines['left'].set_position(('axes', 0.6))
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position(('axes', 0.1))
|
||||
ax.spines['top'].set_color('none')
|
||||
ax.spines['left'].set_smart_bounds(True)
|
||||
ax.spines['bottom'].set_smart_bounds(True)
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
|
||||
ax = fig.add_subplot(2, 2, 4)
|
||||
ax.set_title('spines at data (1, 2)')
|
||||
ax.plot(x, y)
|
||||
ax.spines['left'].set_position(('data', 1))
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position(('data', 2))
|
||||
ax.spines['top'].set_color('none')
|
||||
ax.spines['left'].set_smart_bounds(True)
|
||||
ax.spines['bottom'].set_smart_bounds(True)
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
```
|
||||
|
||||

|
||||
|
||||
定义一个调整轴Spine位置的方法
|
||||
|
||||
```python
|
||||
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
|
||||
spine.set_smart_bounds(True)
|
||||
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([])
|
||||
```
|
||||
|
||||
使用我们的新adjust_spines方法创建另一个图形。
|
||||
|
||||
```python
|
||||
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, clip_on=False)
|
||||
adjust_spines(ax, ['left'])
|
||||
|
||||
ax = fig.add_subplot(2, 2, 2)
|
||||
ax.plot(x, y, clip_on=False)
|
||||
adjust_spines(ax, [])
|
||||
|
||||
ax = fig.add_subplot(2, 2, 3)
|
||||
ax.plot(x, y, clip_on=False)
|
||||
adjust_spines(ax, ['left', 'bottom'])
|
||||
|
||||
ax = fig.add_subplot(2, 2, 4)
|
||||
ax.plot(x, y, clip_on=False)
|
||||
adjust_spines(ax, ['bottom'])
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: spine_placement_demo.py](https://matplotlib.org/_downloads/spine_placement_demo.py)
|
||||
- [下载Jupyter notebook: spine_placement_demo.ipynb](https://matplotlib.org/_downloads/spine_placement_demo.ipynb)
|
||||
53
Python/matplotlab/gallery/ticks_and_spines/spines.md
Normal file
53
Python/matplotlab/gallery/ticks_and_spines/spines.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# Spines图
|
||||
|
||||
这个演示比较:
|
||||
|
||||
- 正常轴,四边都有spine;
|
||||
- 仅在左侧和底部有spine的轴;
|
||||
- 使用自定义边界限制spine范围的轴。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
x = np.linspace(0, 2 * np.pi, 100)
|
||||
y = 2 * np.sin(x)
|
||||
|
||||
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)
|
||||
|
||||
ax0.plot(x, y)
|
||||
ax0.set_title('normal spines')
|
||||
|
||||
ax1.plot(x, y)
|
||||
ax1.set_title('bottom-left spines')
|
||||
|
||||
# Hide the right and top spines
|
||||
ax1.spines['right'].set_visible(False)
|
||||
ax1.spines['top'].set_visible(False)
|
||||
# Only show ticks on the left and bottom spines
|
||||
ax1.yaxis.set_ticks_position('left')
|
||||
ax1.xaxis.set_ticks_position('bottom')
|
||||
|
||||
ax2.plot(x, y)
|
||||
|
||||
# Only draw spine between the y-ticks
|
||||
ax2.spines['left'].set_bounds(-1, 1)
|
||||
# Hide the right and top spines
|
||||
ax2.spines['right'].set_visible(False)
|
||||
ax2.spines['top'].set_visible(False)
|
||||
# Only show ticks on the left and bottom spines
|
||||
ax2.yaxis.set_ticks_position('left')
|
||||
ax2.xaxis.set_ticks_position('bottom')
|
||||
|
||||
# Tweak spacing between subplots to prevent labels from overlapping
|
||||
plt.subplots_adjust(hspace=0.5)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: spines.py](https://matplotlib.org/_downloads/spines.py)
|
||||
- [下载Jupyter notebook: spines.ipynb](https://matplotlib.org/_downloads/spines.ipynb)
|
||||
44
Python/matplotlab/gallery/ticks_and_spines/spines_bounds.md
Normal file
44
Python/matplotlab/gallery/ticks_and_spines/spines_bounds.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# 自定义spine边界
|
||||
|
||||
使用自定义边界来限制脊椎范围的spine演示。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
x = np.linspace(0, 2*np.pi, 50)
|
||||
y = np.sin(x)
|
||||
y2 = y + 0.1 * np.random.normal(size=x.shape)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot(x, y, 'k--')
|
||||
ax.plot(x, y2, 'ro')
|
||||
|
||||
# set ticks and tick labels
|
||||
ax.set_xlim((0, 2*np.pi))
|
||||
ax.set_xticks([0, np.pi, 2*np.pi])
|
||||
ax.set_xticklabels(['0', r'$\pi$', r'2$\pi$'])
|
||||
ax.set_ylim((-1.5, 1.5))
|
||||
ax.set_yticks([-1, 0, 1])
|
||||
|
||||
# Only draw spine between the y-ticks
|
||||
ax.spines['left'].set_bounds(-1, 1)
|
||||
# Hide the right and top spines
|
||||
ax.spines['right'].set_visible(False)
|
||||
ax.spines['top'].set_visible(False)
|
||||
# Only show ticks on the left and bottom spines
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: spines_bounds.py](https://matplotlib.org/_downloads/spines_bounds.py)
|
||||
- [下载Jupyter notebook: spines_bounds.ipynb](https://matplotlib.org/_downloads/spines_bounds.ipynb)
|
||||
36
Python/matplotlab/gallery/ticks_and_spines/spines_dropped.md
Normal file
36
Python/matplotlab/gallery/ticks_and_spines/spines_dropped.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# 掉落的spines
|
||||
|
||||
从轴上偏移的spines的演示(a.k.a。“掉落的spines”)。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
image = np.random.uniform(size=(10, 10))
|
||||
ax.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
|
||||
ax.set_title('dropped spines')
|
||||
|
||||
# Move left and bottom spines outward by 10 points
|
||||
ax.spines['left'].set_position(('outward', 10))
|
||||
ax.spines['bottom'].set_position(('outward', 10))
|
||||
# Hide the right and top spines
|
||||
ax.spines['right'].set_visible(False)
|
||||
ax.spines['top'].set_visible(False)
|
||||
# Only show ticks on the left and bottom spines
|
||||
ax.yaxis.set_ticks_position('left')
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: spines_dropped.py](https://matplotlib.org/_downloads/spines_dropped.py)
|
||||
- [下载Jupyter notebook: spines_dropped.ipynb](https://matplotlib.org/_downloads/spines_dropped.ipynb)
|
||||
113
Python/matplotlab/gallery/ticks_and_spines/tick_formatters.md
Normal file
113
Python/matplotlab/gallery/ticks_and_spines/tick_formatters.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# 刻度格式化程序
|
||||
|
||||
显示不同的刻度格式化程序。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
|
||||
|
||||
# Setup a plot such that only the bottom spine is shown
|
||||
def setup(ax):
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['left'].set_color('none')
|
||||
ax.yaxis.set_major_locator(ticker.NullLocator())
|
||||
ax.spines['top'].set_color('none')
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.tick_params(which='major', width=1.00, length=5)
|
||||
ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
|
||||
ax.set_xlim(0, 5)
|
||||
ax.set_ylim(0, 1)
|
||||
ax.patch.set_alpha(0.0)
|
||||
|
||||
|
||||
fig = plt.figure(figsize=(8, 6))
|
||||
n = 7
|
||||
|
||||
# Null formatter
|
||||
ax = fig.add_subplot(n, 1, 1)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
|
||||
ax.xaxis.set_major_formatter(ticker.NullFormatter())
|
||||
ax.xaxis.set_minor_formatter(ticker.NullFormatter())
|
||||
ax.text(0.0, 0.1, "NullFormatter()", fontsize=16, transform=ax.transAxes)
|
||||
|
||||
# Fixed formatter
|
||||
ax = fig.add_subplot(n, 1, 2)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
|
||||
majors = ["", "0", "1", "2", "3", "4", "5"]
|
||||
ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors))
|
||||
minors = [""] + ["%.2f" % (x-int(x)) if (x-int(x))
|
||||
else "" for x in np.arange(0, 5, 0.25)]
|
||||
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(minors))
|
||||
ax.text(0.0, 0.1, "FixedFormatter(['', '0', '1', ...])",
|
||||
fontsize=15, transform=ax.transAxes)
|
||||
|
||||
|
||||
# FuncFormatter can be used as a decorator
|
||||
@ticker.FuncFormatter
|
||||
def major_formatter(x, pos):
|
||||
return "[%.2f]" % x
|
||||
|
||||
|
||||
ax = fig.add_subplot(n, 1, 3)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
|
||||
ax.xaxis.set_major_formatter(major_formatter)
|
||||
ax.text(0.0, 0.1, 'FuncFormatter(lambda x, pos: "[%.2f]" % x)',
|
||||
fontsize=15, transform=ax.transAxes)
|
||||
|
||||
|
||||
# FormatStr formatter
|
||||
ax = fig.add_subplot(n, 1, 4)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
|
||||
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter(">%d<"))
|
||||
ax.text(0.0, 0.1, "FormatStrFormatter('>%d<')",
|
||||
fontsize=15, transform=ax.transAxes)
|
||||
|
||||
# Scalar formatter
|
||||
ax = fig.add_subplot(n, 1, 5)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.AutoLocator())
|
||||
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
|
||||
ax.xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
|
||||
ax.text(0.0, 0.1, "ScalarFormatter()", fontsize=15, transform=ax.transAxes)
|
||||
|
||||
# StrMethod formatter
|
||||
ax = fig.add_subplot(n, 1, 6)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
|
||||
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x}"))
|
||||
ax.text(0.0, 0.1, "StrMethodFormatter('{x}')",
|
||||
fontsize=15, transform=ax.transAxes)
|
||||
|
||||
# Percent formatter
|
||||
ax = fig.add_subplot(n, 1, 7)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
|
||||
ax.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
|
||||
ax.text(0.0, 0.1, "PercentFormatter(xmax=5)",
|
||||
fontsize=15, transform=ax.transAxes)
|
||||
|
||||
# Push the top of the top axes outside the figure because we only show the
|
||||
# bottom spine.
|
||||
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: tick-formatters.py](https://matplotlib.org/_downloads/tick-formatters.py)
|
||||
- [下载Jupyter notebook: tick-formatters.ipynb](https://matplotlib.org/_downloads/tick-formatters.ipynb)
|
||||
@@ -0,0 +1,30 @@
|
||||
# 在右侧设置默认的y轴刻度标签
|
||||
|
||||
我们可以使用[rcParams["ytick.labelright"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为False)和[rcParams["ytick.right"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为False)和[rcParams["ytick.labelleft"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为True)和 [rcParams["ytick.left"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为True)控制轴上的刻度和标签出现的位置。这些属性也可以在.matplotlib / matplotlibrc中设置。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
plt.rcParams['ytick.right'] = plt.rcParams['ytick.labelright'] = True
|
||||
plt.rcParams['ytick.left'] = plt.rcParams['ytick.labelleft'] = False
|
||||
|
||||
x = np.arange(10)
|
||||
|
||||
fig, (ax0, ax1) = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
|
||||
|
||||
ax0.plot(x)
|
||||
ax0.yaxis.tick_left()
|
||||
|
||||
# use default parameter in rcParams, not calling tick_right()
|
||||
ax1.plot(x)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
-[下载python源码: tick_label_right.py](https://matplotlib.org/_downloads/tick_label_right.py)
|
||||
-[下载Jupyter notebook: tick_label_right.ipynb](https://matplotlib.org/_downloads/tick_label_right.ipynb)
|
||||
@@ -0,0 +1,36 @@
|
||||
# 从值列表中设置刻度标签
|
||||
|
||||
使用ax.set_xticks会导致在当前选择的刻度上设置刻度标签。 但是,您可能希望允许matplotlib动态选择刻度数及其间距。
|
||||
|
||||
在这种情况下,最好从刻度线上的值确定刻度标签。 以下示例显示了如何执行此操作。
|
||||
|
||||
注意:这里使用MaxNLocator来确保刻度值取整数值。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.ticker import FuncFormatter, MaxNLocator
|
||||
fig, ax = plt.subplots()
|
||||
xs = range(26)
|
||||
ys = range(26)
|
||||
labels = list('abcdefghijklmnopqrstuvwxyz')
|
||||
|
||||
|
||||
def format_fn(tick_val, tick_pos):
|
||||
if int(tick_val) in xs:
|
||||
return labels[int(tick_val)]
|
||||
else:
|
||||
return ''
|
||||
|
||||
|
||||
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
|
||||
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
|
||||
ax.plot(xs, ys)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: tick_labels_from_values.py](https://matplotlib.org/_downloads/tick_labels_from_values.py)
|
||||
- [下载Jupyter notebook: tick_labels_from_values.ipynb](https://matplotlib.org/_downloads/tick_labels_from_values.ipynb)
|
||||
106
Python/matplotlab/gallery/ticks_and_spines/tick_locators.md
Normal file
106
Python/matplotlab/gallery/ticks_and_spines/tick_locators.md
Normal file
@@ -0,0 +1,106 @@
|
||||
# 刻度定位器
|
||||
|
||||
显示不同的刻度定位器。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
|
||||
|
||||
# Setup a plot such that only the bottom spine is shown
|
||||
def setup(ax):
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['left'].set_color('none')
|
||||
ax.yaxis.set_major_locator(ticker.NullLocator())
|
||||
ax.spines['top'].set_color('none')
|
||||
ax.xaxis.set_ticks_position('bottom')
|
||||
ax.tick_params(which='major', width=1.00)
|
||||
ax.tick_params(which='major', length=5)
|
||||
ax.tick_params(which='minor', width=0.75)
|
||||
ax.tick_params(which='minor', length=2.5)
|
||||
ax.set_xlim(0, 5)
|
||||
ax.set_ylim(0, 1)
|
||||
ax.patch.set_alpha(0.0)
|
||||
|
||||
|
||||
plt.figure(figsize=(8, 6))
|
||||
n = 8
|
||||
|
||||
# Null Locator
|
||||
ax = plt.subplot(n, 1, 1)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.NullLocator())
|
||||
ax.xaxis.set_minor_locator(ticker.NullLocator())
|
||||
ax.text(0.0, 0.1, "NullLocator()", fontsize=14, transform=ax.transAxes)
|
||||
|
||||
# Multiple Locator
|
||||
ax = plt.subplot(n, 1, 2)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
|
||||
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
|
||||
ax.text(0.0, 0.1, "MultipleLocator(0.5)", fontsize=14,
|
||||
transform=ax.transAxes)
|
||||
|
||||
# Fixed Locator
|
||||
ax = plt.subplot(n, 1, 3)
|
||||
setup(ax)
|
||||
majors = [0, 1, 5]
|
||||
ax.xaxis.set_major_locator(ticker.FixedLocator(majors))
|
||||
minors = np.linspace(0, 1, 11)[1:-1]
|
||||
ax.xaxis.set_minor_locator(ticker.FixedLocator(minors))
|
||||
ax.text(0.0, 0.1, "FixedLocator([0, 1, 5])", fontsize=14,
|
||||
transform=ax.transAxes)
|
||||
|
||||
# Linear Locator
|
||||
ax = plt.subplot(n, 1, 4)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.LinearLocator(3))
|
||||
ax.xaxis.set_minor_locator(ticker.LinearLocator(31))
|
||||
ax.text(0.0, 0.1, "LinearLocator(numticks=3)",
|
||||
fontsize=14, transform=ax.transAxes)
|
||||
|
||||
# Index Locator
|
||||
ax = plt.subplot(n, 1, 5)
|
||||
setup(ax)
|
||||
ax.plot(range(0, 5), [0]*5, color='White')
|
||||
ax.xaxis.set_major_locator(ticker.IndexLocator(base=.5, offset=.25))
|
||||
ax.text(0.0, 0.1, "IndexLocator(base=0.5, offset=0.25)",
|
||||
fontsize=14, transform=ax.transAxes)
|
||||
|
||||
# Auto Locator
|
||||
ax = plt.subplot(n, 1, 6)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.AutoLocator())
|
||||
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
|
||||
ax.text(0.0, 0.1, "AutoLocator()", fontsize=14, transform=ax.transAxes)
|
||||
|
||||
# MaxN Locator
|
||||
ax = plt.subplot(n, 1, 7)
|
||||
setup(ax)
|
||||
ax.xaxis.set_major_locator(ticker.MaxNLocator(4))
|
||||
ax.xaxis.set_minor_locator(ticker.MaxNLocator(40))
|
||||
ax.text(0.0, 0.1, "MaxNLocator(n=4)", fontsize=14, transform=ax.transAxes)
|
||||
|
||||
# Log Locator
|
||||
ax = plt.subplot(n, 1, 8)
|
||||
setup(ax)
|
||||
ax.set_xlim(10**3, 10**10)
|
||||
ax.set_xscale('log')
|
||||
ax.xaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=15))
|
||||
ax.text(0.0, 0.1, "LogLocator(base=10, numticks=15)",
|
||||
fontsize=15, transform=ax.transAxes)
|
||||
|
||||
# Push the top of the top axes outside the figure because we only show the
|
||||
# bottom spine.
|
||||
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: tick-locators.py](https://matplotlib.org/_downloads/tick-locators.py)
|
||||
- [下载Jupyter notebook: tick-locators.ipynb](https://matplotlib.org/_downloads/tick-locators.ipynb)
|
||||
@@ -0,0 +1,30 @@
|
||||
# 在顶部设置默认的x轴刻度标签
|
||||
|
||||
我们可以使用 [rcParams["xtick.labeltop"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为False)和[rcParams["xtick.top"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为False)和[rcParams["xtick.labelbottom"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)(默认为True)和 [rcParams["xtick.bottom"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams) (默认为True)控制轴上的刻度和标签出现的位置。
|
||||
|
||||
这些属性也可以在.matplotlib / matplotlibrc中设置。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
|
||||
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
|
||||
|
||||
x = np.arange(10)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
ax.plot(x)
|
||||
ax.set_title('xlabel top') # Note title moves to make room for ticks
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: tick_xlabel_top.py](https://matplotlib.org/_downloads/tick_xlabel_top.py)
|
||||
- [下载Jupyter notebook: tick_xlabel_top.ipynb](https://matplotlib.org/_downloads/tick_xlabel_top.ipynb)
|
||||
@@ -0,0 +1,28 @@
|
||||
# 旋转自定义刻度标签
|
||||
|
||||
使用用户定义的旋转演示自定义刻度标签。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
x = [1, 2, 3, 4]
|
||||
y = [1, 4, 9, 6]
|
||||
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']
|
||||
|
||||
plt.plot(x, y, 'ro')
|
||||
# You can specify a rotation for the tick labels in degrees or with keywords.
|
||||
plt.xticks(x, labels, rotation='vertical')
|
||||
# Pad margins so that markers don't get clipped by the axes
|
||||
plt.margins(0.2)
|
||||
# Tweak spacing to prevent clipping of tick-labels
|
||||
plt.subplots_adjust(bottom=0.15)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: ticklabels_rotation.py](https://matplotlib.org/_downloads/ticklabels_rotation.py)
|
||||
- [下载Jupyter notebook: ticklabels_rotation.ipynb](https://matplotlib.org/_downloads/ticklabels_rotation.ipynb)
|
||||
Reference in New Issue
Block a user