【问题标题】:Is there a quick way to set the legend of a scatterplot without looping?有没有一种快速的方法来设置散点图的图例而不循环?
【发布时间】:2020-09-27 07:01:16
【问题描述】:

我有 3 个这样的数组:

x = [1,2,3,4,5]
y = [5,4,3,2,1]
c = [0,0,1,0,1]

plt.figure(figsize = (12,9))

plt.scatter(x = x, y = y, c = c)

plt.legend(['0', '1'])

我能够生成这样的散点图:

但我想要的是它能够区分 0 和 1 之间的颜色。

解决方案here 在类上执行 for 循环以达到预期的结果。 我也尝试过迭代 plt.scatter() 对象,但它不可迭代。

那里有某种简单的解决方案吗?最好没有循环,只有大约 1 行代码?

【问题讨论】:

    标签: python matplotlib scatter-plot


    【解决方案1】:

    还没有。但 Matplotlib 很快就会发布一个带有简单 scatter + legend 的 scatter 版本,无需多次调用。

    请注意,您还可以使用 the Seaborn scatterplot function 来生成带有单行标签的散点图(请参阅下面的 Seaborn 文档):

    sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
    

    【讨论】:

      【解决方案2】:

      您可以使用适当的标签逐一循环和绘制所有不同的数据集。 在这里,我先绘制红点,然后绘制绿色点。

      import matplotlib.pyplot as plt
      x = [1,2,3,4,5]
      y = [5,4,3,2,1]
      c = [0,0,1,0,1]
      
      unique = list(set(c))
      colors = ['red','green']
      for i, u in enumerate(unique):
          xi = [x[j] for j  in range(len(x)) if c[j] == u]
          yi = [y[j] for j  in range(len(x)) if c[j] == u]
          plt.scatter(xi, yi, c=colors[i], label=str(u))
      plt.legend()
      
      plt.show()
      

      【讨论】:

      • 是的,但问题是要实现它不循环...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 2013-05-15
      • 1970-01-01
      • 2015-06-30
      • 2011-09-24
      • 1970-01-01
      相关资源
      最近更新 更多