简体   繁体   中英

Legend colors mismatch plot colors

I'm trying to set up the legends of each points in the scatter plot. My main problem is that the colors of each point do not match the color of what is in the legend. What am I doing wrong and how do I rectify it?

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()

It seems like you might be trying to plot groups in a dataframe. So something like this might work:

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()

This produces:

样本图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM