为啥我要绘制的代码没有显示带有标题、xlabel 和 ylabel 的输出?

Posted

技术标签:

【中文标题】为啥我要绘制的代码没有显示带有标题、xlabel 和 ylabel 的输出?【英文标题】:Why my code to plot is not showing the output with the titles, xlabel and ylabel?为什么我要绘制的代码没有显示带有标题、xlabel 和 ylabel 的输出? 【发布时间】:2019-12-17 05:19:54 【问题描述】:

我尝试使用matplotlib 绘制条形图,但是当我编写代码以显示标题和 xlabel-ylabel 时,它们没有显示。我做错了什么?

我创建了一个数据框并尝试使用df.plot(...) 绘制相同的图。 但是后来我没有得到标签选项和xticks。这就是我尝试这个的原因。

# Make a fake dataset:
districts = ['Alappuzha','Ernakulam','Idukki','Kannur','Kasaragod','Kollam','Kottayam','Kozhikode','Malappuram','Palakkad','Pathanamthitta','Thiruvananthapuram','Wayanad','Thrissur']
distAb = ['Alp','Ern','Idk','Knr','Ksd','Klm','Ktm','Kzd','Mlp','Plk','Pta','Tvm','Wyd','Tsr']
population = [2121943,3279860,1107453,2525637,1302600,2629703,1979384,3089543,4110956,2810892,1195537,3307284,816558,3110327]
posArrange = np.arange(len(districts))

创建条形

plt.bar(posArrange,population,color='#ff9900', width=.8)


plt.title='Population of Districts in Kerala'
plt.xlabel='Districts'
plt.ylabel='Population'
plt.xticks(posArrange,distAb)

显示图形

plt.show()

输出不是我所期望的。它没有显示 xlabel、ylabel 和标题。 enter image description here

【问题讨论】:

plt.title 是一个函数。你需要调用它。 plt.title("My title") 我刚才也试过了.. 但显示错误 TypeError: 'str' object is not callable 当然,因为在你为它分配了一个字符串的那一刻,它不再是一个函数了。 我从 import matplotlib.pyplot as plt 开始再次运行单元格。但同样的错误 尝试重新启动内核,然后尝试代码。 【参考方案1】:

titlexlabelylabelxticks 是函数,这意味着它们后面跟有带参数的括号。 相应地更改以下行,您应该会在绘图中看到所需的元素。

plt.title('Population of Districts in Kerala')
plt.xlabel('Districts')
plt.ylabel('Population')
plt.xticks(posArrange,distAb)
plt.show()

【讨论】:

我已重新分配给字符串。我试图重新启动我的 google.colab 的内核,但仍然出现错误... TypeError: 'str' object is not callable 我可以确认来自 Arienrhod 的结果。如果您仍然收到 'TypeError: 'str' object is not callable' 错误消息,那么您的环境尚未正确设置。尝试通过输出变量“plt.title”来检查这一点。如果它返回“喀拉拉邦地区人口”,那么您还没有真正重新启动内核。正确重启内核后,如果您调用 plt.title 它应该返回类似 【参考方案2】:

我在我的项目中使用了以下代码并且它正在工作。你可以像这样使用相同的

import matplotlib.pyplot as plt 
left = [1, 2, 3, 4]
height = [logistic_score*100,naive_score*100,svm_score*100,mlp_score*100] 
tick_label = ['Logistic Regression', 'Naive Bayes', 'SVM', 'Multi linear 
perceptron'] 
plt.bar(left, height, tick_label = tick_label, width = 0.3, color = ['red', 
'green','blue','violet'])
plt.xlabel('Algorithms')
plt.ylabel('Efficiency')
plt.title('Results Comaprision') 
plt.show()

【讨论】:

以上是关于为啥我要绘制的代码没有显示带有标题、xlabel 和 ylabel 的输出?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在 GLFW 窗口中使用此代码在我的屏幕上没有绘制立方体?

子图和 xlabel 中的标题

为啥 vim 在制表符的位置绘制下划线以及如何避免这种情况?

为啥 PyGame 在延迟或睡眠之前没有在窗口中绘制?

为啥 <img [src]> 没有在带有 *ngFor 循环的 <ion col> 内部显示?

为啥我无法显示已单击列表视图?如何让展示成为可能?