首页 > 解决方案 > 图例颜色不匹配绘图颜色

问题描述

我正在尝试设置散点图中每个点的图例。我的主要问题是每个点的颜色与图例中的颜色不匹配。我做错了什么,我该如何纠正?

def scatter(self, indep, dep, labl):
   x = self.df_input[indep]
   y = self.df_input[dep]
   random = np.random.RandomState(0)
   colors = random.rand(len(labl)+1)

   fig = plt.figure()
   ax = fig.add_subplot(111)

   for leg in labl:
      ax.scatter(x, y, c=colors, cmap='gist_ncar', label=leg)

   ax.legend()
   ax.set_xlabel(indep)
   ax.set_ylabel(dep)
   ax.axis('tight')
   plt.show()

标签: pythonmatplotlibplotscatter-plot

解决方案


似乎您可能正在尝试在数据框中绘制组。所以这样的事情可能会起作用:

import matplotlib.pyplot as plt
import pandas as pd

data = [['a', 1, 3],
        ['a', 2, 2],
        ['b', 2, 4],
        ['b', 1, 5],
        ['b', 3, 5],
       ]

df = pd.DataFrame(data, columns=['cat', 'x', 'y'])

for name, group in df.groupby('cat'):
    plt.scatter(group.x, group.y, label=name)
plt.legend()

这会产生:

样本图


推荐阅读