Matplotlib与轴的传说

问题描述 投票:0回答:1

当谈到在它上面添加一个图例时,我很难用这个特定的情节。我已经回顾了类似的问题,但我没有看到任何挑战是如何在附加到轴对象的图例上标记三个元素(如条形图)。

我如何添加一个图例,以便第一个栏显示为“训练错误”,第二个栏显示为“Val Errors”,第三个栏显示为“Test Errors”?

plt.figure(figsize=(20,10))
ax = plt.subplot(111)

x1 = [i-0.2 for i in range(len(train_errors))]
x2 = [i for i in range(len(train_errors))]
x3 = [i+0.2 for i in range(len(train_errors))]

ax.bar(x1, train_errors, width=0.2, color='b', align='center')
ax.bar(x2, val_errors, width=0.2, color='g', align='center')
ax.bar(x3, test_errors, width=0.2, color='r', align='center')
ax.set_xticklabels(X)
ax.xaxis.set_major_locator(ticker.FixedLocator([i-0.05 for i in x2]))

ax.legend((bar), ('label1'))

ax.set_xlabel('Models')
ax.set_ylabel('RMSE')
ax.set_title('Regression Models Comparison')
plt.show()

谢谢!

python matplotlib legend axis
1个回答
1
投票

通过指定label参数,可以创建类似于许多其他艺术家的条形图的图例条目。

ax.bar(...., label="my label")
ax.legend()

这也在the documentation的第一个例子中显示。

完整的例子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

train_errors = [1,2,3,4,5]
val_errors = [2,1,4,2,3]
test_errors = [5,4,3,2,1]
X = list("ABCDE")

x1 = [i-0.2 for i in range(len(train_errors))]
x2 = [i for i in range(len(train_errors))]
x3 = [i+0.2 for i in range(len(train_errors))]

ax.bar(x1, train_errors, width=0.2, color='b', label="Train Errors")
ax.bar(x2, val_errors, width=0.2, color='g', label="Val Errors")
ax.bar(x3, test_errors, width=0.2, color='r', label="Test Errors")

ax.set_xticks(x2)
ax.set_xticklabels(X)

ax.legend()

ax.set_xlabel('Models')
ax.set_ylabel('RMSE')
ax.set_title('Regression Models Comparison')
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.