轴不能移动到另一个图形。推荐的方法是将ax 作为参数提供给draw(....., ax=...)。
代码结构如下:
from matplotlib import pyplot as plt
def draw(data, size=7, ax=None):
if ax is None:
ax = plt.gca() # use current axis if none is given
ax.scatter(data['x'], data['y'], s=size, c=data['c'], linewidths=0, alpha=0.9)
ax.grid(False)
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
draw(data_1, ax=axes[0])
draw(data_2, ax=axes[1])
fig.show()
通常还提供scatter 的参数。 Python 通过**kwargs 支持这些额外的关键字并将它们转换为字典。对于scatter 的参数不是用户提供的,draw 函数可以设置自己的默认值。这是一个更详细的示例:
from matplotlib import pyplot as plt
import numpy as np
def draw(data, size=7, ax=None, **kwargs):
if ax is None:
ax = plt.gca() # use current axis if none is given
print(kwargs)
if 's' not in kwargs:
kwargs['s'] = 7
if 'linewidths' not in kwargs:
kwargs['linewidths'] = 0
if 'alpha' not in kwargs:
kwargs['alpha'] = 0.9
print(kwargs)
ax.scatter(data['x'], data['y'], c=data['c'], **kwargs)
ax.grid(False)
data_1 = {'x': np.random.rand(800), 'y': np.random.rand(800), 'c': np.random.rand(800)}
data_2 = {'x': np.random.rand(200), 'y': np.random.rand(200), 'c': np.random.rand(200)}
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
draw(data_1, ax=axes[0])
draw(data_2, ax=axes[1], linewidths=1, edgecolor='gold', s=20)
fig.show()