plt.scatter label设置注释字体颜色
时间: 2024-03-27 21:33:06 浏览: 105
在使用matplotlib库的plt.scatter函数时,可以通过设置label参数来添加注释。要设置注释字体颜色,可以使用plt.text函数来实现。具体步骤如下:
1. 首先,使用plt.scatter函数创建散点图,并设置label参数为注释内容。
```python
plt.scatter(x, y, label='注释内容')
```
2. 然后,使用plt.text函数来添加注释,并设置color参数为所需的字体颜色。
```python
plt.text(x, y, '注释内容', color='字体颜色')
```
其中,x和y分别表示注释的位置坐标。
下面是一个完整的示例代码:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.scatter(x, y, label='散点图')
plt.text(3, 6, '注释内容', color='red')
plt.legend()
plt.show()
```
这样就可以在散点图上添加注释,并设置注释字体的颜色了。
相关问题
KNN=KNearestNeighbor() KNN.train(X_train, y_train) y_pred = KNN.predict(X_test, k=6) accuracy = np.mean(y_pred == y_test) print('测试集预测准确率:%f' % accuracy) plt.scatter(X_setosa_train[:, 0], X_setosa_train[:, 2], color='red', marker='o', label='setosa_train') plt.scatter(X_versicolor_train[:, 0], X_versicolor_train[:, 2], color='blue', marker='^', label='versicolor_train') plt.scatter(X_virginica_train[:, 0], X_virginica_train[:, 2], color='green', marker='s', label='virginica_train') plt.scatter(X_setosa_test[:, 0], X_setosa_test[:, 2], color='y', marker='o', label='setosa_test') plt.scatter(X_versicolor_test[:, 0], X_versicolor_test[:, 2], color='y', marker='^', label='versicolor_test') plt.scatter(X_virginica_test[:, 0], X_virginica_test[:, 2], color='y', marker='s', label='virginica_test') plt.xlabel('sepal length') plt.ylabel('petal length') plt.legend(loc = 4) plt.show()注释每一行代码
以下是对每一行代码的注释:
```python
# 初始化 KNN 模型
KNN = KNearestNeighbor()
# 使用训练集数据进行模型训练
KNN.train(X_train, y_train)
# 使用测试集数据进行预测,并指定 k=6
y_pred = KNN.predict(X_test, k=6)
# 计算模型的准确率
accuracy = np.mean(y_pred == y_test)
# 绘制散点图,展示不同种类的花的数据分布
plt.scatter(X_setosa_train[:, 0], X_setosa_train[:, 2], color='red', marker='o', label='setosa_train')
plt.scatter(X_versicolor_train[:, 0], X_versicolor_train[:, 2], color='blue', marker='^', label='versicolor_train')
plt.scatter(X_virginica_train[:, 0], X_virginica_train[:, 2], color='green', marker='s', label='virginica_train')
plt.scatter(X_setosa_test[:, 0], X_setosa_test[:, 2], color='y', marker='o', label='setosa_test')
plt.scatter(X_versicolor_test[:, 0], X_versicolor_test[:, 2], color='y', marker='^', label='versicolor_test')
plt.scatter(X_virginica_test[:, 0], X_virginica_test[:, 2], color='y', marker='s', label='virginica_test')
# 设置 x 轴和 y 轴的标签
plt.xlabel('sepal length')
plt.ylabel('petal length')
# 显示图例,并设置其位置
plt.legend(loc = 4)
# 显示图形
plt.show()
```
d2l.plt.scatter()是什么函数
d2l.plt.scatter() 是 Deep Learning - The Straight Dope (D2L) 书中定义的一个函数,用于绘制散点图。它是基于 Matplotlib 库实现的,具有以下特点:
- 支持自定义点的颜色、大小、形状等属性。
- 支持添加标题、坐标轴标签等注释。
- 支持同时绘制多个散点图。
该函数的定义如下:
```python
def set_figsize(figsize=(3.5, 2.5)):
"""Set matplotlib figure size."""
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize
def use_svg_display():
"""Use svg format to display plot in jupyter."""
d2l.plt.rcParams['svg.fonttype'] = 'none'
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear', fmts=None,
figsize=(3.5, 2.5), axes=None):
"""Plot multiple lines."""
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
# Return True if X (tensor or list) has more than 1 dimension
def has_one_dim(X):
if isinstance(X, np.ndarray) or isinstance(X, list):
return len(X.shape) == 1
else:
return len(X.size()) == 1
# Convert Y to list so that len(Y) is always defined
if Y is None:
Y = []
if not isinstance(Y, list):
Y = [Y]
if not isinstance(X, list):
X = [X] * len(Y)
if len(X) != len(Y):
X = X * len(Y)
# Format lines and points
if fmts is None:
fmts = ['-'] * len(X)
elif isinstance(fmts, str):
fmts = [fmts] * len(X)
# Plot
for x, y, fmt in zip(X, Y, fmts):
if has_one_dim(x):
x = np.arange(len(y)) + 1
axes.plot(x, y, fmt)
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
if xlim:
axes.set_xlim(xlim)
if ylim:
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
d2l.plt.show()
def show_images(imgs, num_rows, num_cols, scale=2):
"""Plot a list of images."""
figsize = (num_cols * scale, num_rows * scale)
_, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
for i in range(num_rows):
for j in range(num_cols):
axes[i][j].imshow(imgs[i * num_cols + j])
axes[i][j].axes.get_xaxis().set_visible(False)
axes[i][j].axes.get_yaxis().set_visible(False)
return axes
def plot_learning_curves(train_acc, test_acc, train_loss, test_loss):
"""Plot the learning curves."""
d2l.plt.plot(train_acc, linestyle='-', color='blue', label='train accuracy')
d2l.plt.plot(test_acc, linestyle='--', color='red', label='test accuracy')
d2l.plt.xlabel('epochs')
d2l.plt.ylabel('accuracy')
d2l.plt.legend(loc='upper right')
d2l.plt.twinx()
d2l.plt.plot(train_loss, linestyle='-', color='green', label='train loss')
d2l.plt.plot(test_loss, linestyle='--', color='orange', label='test loss')
d2l.plt.ylabel('loss')
d2l.plt.legend(loc='upper left')
d2l.plt.show()
def use_svg_display():
"""Use svg format to display plot in jupyter."""
d2l.plt.rcParams['svg.fonttype'] = 'none'
def set_figsize(figsize=(3.5, 2.5)):
"""Set matplotlib figure size."""
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear', fmts=None,
figsize=(3.5, 2.5), axes=None):
"""Plot multiple lines."""
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
# Return True if X (tensor or list) has more than 1 dimension
def has_one_dim(X):
if isinstance(X, np.ndarray) or isinstance(X, list):
return len(X.shape) == 1
else:
return len(X.size()) == 1
# Convert Y to list so that len(Y) is always defined
if Y is None:
Y = []
if not isinstance(Y, list):
Y = [Y]
if not isinstance(X, list):
X = [X] * len(Y)
if len(X) != len(Y):
X = X * len(Y)
# Format lines and points
if fmts is None:
fmts = ['-'] * len(X)
elif isinstance(fmts, str):
fmts = [fmts] * len(X)
# Plot
for x, y, fmt in zip(X, Y, fmts):
if has_one_dim(x):
x = np.arange(len(y)) + 1
axes.plot(x, y, fmt)
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
if xlim:
axes.set_xlim(xlim)
if ylim:
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
d2l.plt.show()
def show_images(imgs, num_rows, num_cols, scale=2):
"""Plot a list of images."""
figsize = (num_cols * scale, num_rows * scale)
_, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
for i in range(num_rows):
for j in range(num_cols):
axes[i][j].imshow(imgs[i * num_cols + j])
axes[i][j].axes.get_xaxis().set_visible(False)
axes[i][j].axes.get_yaxis().set_visible(False)
return axes
def plot_learning_curves(train_acc, test_acc, train_loss, test_loss):
"""Plot the learning curves."""
d2l.plt.plot(train_acc, linestyle='-', color='blue', label='train accuracy')
d2l.plt.plot(test_acc, linestyle='--', color='red', label='test accuracy')
d2l.plt.xlabel('epochs')
d2l.plt.ylabel('accuracy')
d2l.plt.legend(loc='upper right')
d2l.plt.twinx()
d2l.plt.plot(train_loss, linestyle='-', color='green', label='train loss')
d2l.plt.plot(test_loss, linestyle='--', color='orange', label='test loss')
d2l.plt.ylabel('loss')
d2l.plt.legend(loc='upper left')
d2l.plt.show()
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
"""Set the axes for matplotlib."""
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
if xlim:
axes.set_xlim(xlim)
if ylim:
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
阅读全文