我正在尝试为我的散点图创建一个与图中设置的颜色相匹配的图例。当我运行我的代码时,我得到两个图,颜色不匹配。有人可以帮我解决这个问题吗?
#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)])
我不确定这是不是你的问题。但我在这里发现了两个问题:
plt.table
之后打电话给plt.show()
。 plt.show()
将根据之前的行显示你的数字而没有表格。 plt.table
将只用桌子制作一个新的情节。这就解释了为什么你“得到两块地块”。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()