带有图例的Python散点图

问题描述 投票:1回答:1

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

#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)])

enter image description here

enter image description here

python pandas matplotlib
1个回答
0
投票

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

  1. 你在plt.table之后打电话给plt.show()plt.show()将根据之前的行显示你的数字而没有表格。 plt.table将只用桌子制作一个新的情节。这就解释了为什么你“得到两块地块”。
  2. 你的set(dfwl.whichballot)只有两个值[0, 1]。因此,您的图例将仅显示rowColours的索引0和1处的颜色,即['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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.