带有图例的Python散点图

里尔孔42

我正在尝试为散点图创建与图例中设置的颜色匹配的图例。当我运行代码时,会得到两个图,并且颜色不匹配。有人可以帮我解决这个问题吗?

#import files and format them (you can skip this- its just simulating my dataset)
import matplotlib.pyplot as plt
import pandas as pd
d = {'vote': [100, 50,1,23,55,67,89,44], 
     'ballot': ['a','Yes','a','No','b','a','a','b'],
     'whichballot':[1,2,1,1,2,1,1,2]}
dfwl=pd.DataFrame(d)

dfwl['whichballot'] = dfwl['whichballot'].astype('category').cat.codes
dfwl['ballot'] = dfwl['ballot'].astype('category')
dfwl['vote'] = dfwl['vote'].astype('int')
dfwl=pd.DataFrame(dfwl.reset_index())
dfwl=dfwl[pd.notnull(dfwl['ballot'])] 
###END DATA FORMATTING    

plt.scatter(dfwl.ballot, dfwl.vote, c=dfwl.whichballot)
plt.margins(x=0.8)
plt.show()
plt.table(cellText=[[x] for x in set(dfwl.whichballot)], 
          loc='lower right',
          colWidths=[0.2],
          rowColours=['green','yellow','purple'],
        rowLabels=['label%d'%x for x in set(dfwl.whichballot)])

在此处输入图片说明

在此处输入图片说明

Y. Luo

我不确定这是否是您的问题。但是我在这里发现了两个问题:

  1. 你叫plt.tableplt.show()plt.show()将根据之前的表格(不带表格)显示您的图形。plt.table将仅用表格绘制一个新图。这就解释了为什么您要“得到两个图”。

  2. set(dfwl.whichballot)只有两个值[0, 1]因此,图例只会在索引0和1处显示颜色rowColours,即['green','yellow']purple在这里没用。

这是带有简单编辑的代码,可能会为您提供所需的内容:

import matplotlib.pyplot as plt
import pandas as pd
d = {'vote': [100, 50,1,23,55,67,89,44], 
     'ballot': ['a','Yes','a','No','b','a','a','b'],
     'whichballot':[1,2,1,1,2,1,1,2]}
dfwl=pd.DataFrame(d)

dfwl['whichballot'] = dfwl['whichballot'].astype('category').cat.codes
dfwl['ballot'] = dfwl['ballot'].astype('category')
dfwl['vote'] = dfwl['vote'].astype('int')
dfwl=pd.DataFrame(dfwl.reset_index())
dfwl=dfwl[pd.notnull(dfwl['ballot'])] 
###END DATA FORMATTING    

plt.scatter(dfwl.ballot, dfwl.vote, c=dfwl.whichballot)
plt.margins(x=0.8)
plt.table(cellText=[[x] for x in set(dfwl.whichballot)], 
          loc='lower right',
          colWidths=[0.2],
          rowColours=['purple','yellow','green'],
          rowLabels=['label%d'%x for x in set(dfwl.whichballot)])
plt.show()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章