【问题标题】:Is there some way can add label in legend in plot by one step?有什么方法可以一步一步在图例中添加标签吗?
【发布时间】:2021-07-14 09:21:20
【问题描述】:

我的传奇现在显示,

我想在图例中添加我的标签,从 0 到 7,但我不想在我的代码中添加一个 for 循环并逐步更正每个标签,我的代码就是这样,

fig, ax = plt.subplots()
ax.set_title('Clusters by OPTICS in 2D space after PCA')
ax.set_xlabel('First Component')
ax.set_ylabel('Second Component')
points = ax.scatter(
    pca_2_spec[:,0], 
    pca_2_spec[:,1],
    s = 7,
    marker='o',
    c = pred_pca_2_spec,
    cmap= 'rainbow')
ax.legend(*points.legend_elements(), title = 'cluster')  
plt.show()

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

    假设 pred_pca_2_spec 是一些 np.array,其值为 [0, 5, 10, 15, 20, 30, 35] 以将这些值更改为 0-7 范围内,只需将(每个元素)除以 5。

    样本数据:

    import numpy as np
    from matplotlib import pyplot as plt
    
    np.random.seed(54)
    pca_2_spec = np.random.randint(-100, 300, (100, 2))
    pred_pca_2_spec = np.random.choice([0, 5, 10, 15, 20, 25, 30, 35], 100)
    

    绘图代码:

    fig, ax = plt.subplots()
    ax.set_title('Clusters by OPTICS in 2D space after PCA')
    ax.set_xlabel('First Component')
    ax.set_ylabel('Second Component')
    points = ax.scatter(
        pca_2_spec[:, 0],
        pca_2_spec[:, 1],
        s=7,
        marker='o',
        c=pred_pca_2_spec / 5,  # Divide By 5
        cmap='rainbow')
    ax.legend(*points.legend_elements(), title='cluster')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2010-09-29
      相关资源
      最近更新 更多