2017-10-08 31 views
0

下面的代码是让谁得到拒绝,并在特定学年招收女生总数:的Python 3.0熊猫和Matplotlib:巴()等matplotlib地块不接受字符串数据帧指数为x轴

query1=All_Females_count[['Admit','Freq']].groupby('Admit').sum() 
print(query1) 
query1.set_index(data.Admit.unique()) 
query1.plot(kind='bar') 

上面的代码似乎工作没关系,给我柱状图预期。但是,下面的代码不会:

Admit Gender Dept Freq 
2 Admitted Female A 89 
3 Rejected Female A 19 
6 Admitted Female B 17 
7 Rejected Female B 8 
10 Admitted Female C 202 
11 Rejected Female C 391 
14 Admitted Female D 131 
15 Rejected Female D 244 
18 Admitted Female E 94 
19 Rejected Female E 299 
22 Admitted Female F 24 
23 Rejected Female F 317 

谁能告诉我为什么:作为如下

plt.bar(query1.index,query1.Freq) 
plt.show() 

All_Females_count数据帧?唯一的解决方法是使用带有数字数据的标签吗?

我还发现此讨论主题:https://github.com/matplotlib/matplotlib/issues/2516/ 对同一主题。

这是一个非常类似的问题。但是,它没有解决我的问题:Using a Pandas dataframe index as values for x-axis in matplotlib plot

回答

0

matplotlib通常需要其x轴的数值。作为the documentation for plt.bar()国家(重点煤矿):

×:标量

酒吧的x坐标序列。

一个相当简单的方式重现pandas的行为是从0索引调用bar()用列表值的个数,然后用该指数的实际内容替换蜱标签。

plt.bar(range(len(query1.index)),query1.Freq) 
plt.xticks(range(len(query1.index)), query1.index) 
plt.show() 
+0

太谢谢你了!它的作品像一个魅力:) –

+0

很高兴听到。如果你觉得你的问题已经解决,考虑接受使用绿色刻度线关闭该线程 –

+0

我绝对会得到答案的一个,但我是很新的计算器:( –

0

要在条形图上获取标签,您需要将数值提供给第一个参数。标签可以使用tick_labels参数进行设置。

import matplotlib.pyplot as plt 

x = list("ABC") 
y = [1,3,4] 

plt.bar(range(len(y)), y, tick_label=x) 

plt.show()