【问题标题】:how can I match legend colors with plot colors?如何将图例颜色与绘图颜色匹配?
【发布时间】:2021-08-09 05:33:04
【问题描述】:

我正在使用一个非常简单的示例。我在同一组轴上创建了三个散点图,并且我绘制的每个数据集都有一个不同的关联颜色图。然而,这个传说看起来并不像我想要的那样。这是为什么呢?

import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs

X, y = make_blobs(n_samples=500, n_features=2, cluster_std=1.0, centers=[(0,0), (3,3)])

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='rainbow');


clf_tree = DecisionTreeClassifier(criterion='entropy', max_depth=1)
clf_tree = clf_tree.fit(X, y)
y_pred = clf_tree.predict(X)

clf_tree = DecisionTreeClassifier(criterion='entropy', min_samples_leaf = 3)
clf_tree = clf_tree.fit(X, y)
y_pred = clf_tree.predict(X)

clf_tree = DecisionTreeClassifier(criterion='entropy', max_leaf_nodes = 3)
clf_tree = clf_tree.fit(X, y)
y_pred = clf_tree.predict(X)



#shap.decision_plot(expected_value, sh, features_display, link='logit', highlight=misclassified)

for i in range(len(y)):
    if y[i] != y_pred[i]:
        plt.scatter(X[i, 0], X[i, 1], c=y[i], s=50, cmap='Dark2')
plt.legend(("0","1","miss"))

【问题讨论】:

  • 您想按照code here 进行操作。关键元素是在绘制每个系列时标记它,然后显示图例。当您最后调用legend() 时,您不应该传递任何参数,它会自动从绘制的数据中提取它们,只要您在绘制数据时标记该数据。

标签: python legend scatter-plot


【解决方案1】:

您可以像这样手动设置它们:

plt.legend(("0","1","miss"))
ax = plt.gca()
leg = ax.get_legend()
leg.legendHandles[0].set_color('purple')
leg.legendHandles[1].set_color('red')
leg.legendHandles[2].set_color('green')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2020-01-21
    • 2021-04-27
    相关资源
    最近更新 更多