matplotlib 绘图-barChart
?matplotlib 是python最著名的繪圖庫(kù),它提供了一整套和matlab相似的命令A(yù)PI,十分適合交互式地進(jìn)行制圖。而且也可以方便地將它作為繪圖控件,嵌入GUI應(yīng)用程序中。它的文檔相當(dāng)完備,并且 Gallery頁(yè)面 中有上百幅縮略圖,打開(kāi)之后都有源程序。因此如果你需要繪制某種類型的圖,只需要在這個(gè)頁(yè)面中瀏覽/復(fù)制/粘貼一下,基本上都能搞定。
現(xiàn)在我們從最簡(jiǎn)單的例子開(kāi)始講解,
import matplotlib.pyplot as plt plt.xlabel('sex') plt.ylabel('number') plt.bar(left = (0,1),height=(0.8,0.5),width=0.25) plt.show()
left:表示左邊緣上的值,
height: 表示y軸上的值,
width:表示矩形bar的寬度
使用plt.xlabel和plt.ylabel來(lái)說(shuō)明x和y軸坐標(biāo)意義。
下面通過(guò)plt.xticks來(lái)說(shuō)明x軸每條bar分別代表的意義,
使用align對(duì)說(shuō)明的位置進(jìn)行控制
import matplotlib.pyplot as plt plt.xlabel('sex') plt.ylabel('number') plt.xticks((0,1),('male','female')) plt.bar(left = (0,1),height=(0.8,0.5),width=0.25,align = 'center') plt.show()接下來(lái)通過(guò)plt.title給繪制的圖像添加標(biāo)題
最后還有就是對(duì)Y軸每條bar上添加對(duì)應(yīng)值的顯示,同時(shí)添加 legend,通過(guò)plt.bar中的參數(shù)yerr設(shè)置y軸突出的長(zhǎng)度。
import matplotlib.pyplot as plt def autolabel(rects):for rect in rects:height = rect.get_height()plt.text(rect.get_x()+rect.get_width()/2.,1.04*height,'%s'%float(height)) plt.xlabel('sex') plt.ylabel('number') plt.xticks((0,1),('male','female')) plt.title('sex ratio analysis') rect = plt.bar(left = (0,1),height=(0.8,0.5),width=0.25,align = 'center',yerr = 0.0001) plt.legend(rect,['legend11'],bbox_to_anchor = (0.95,0.95)) autolabel(rect) plt.show()
總結(jié)
以上是生活随笔為你收集整理的matplotlib 绘图-barChart的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。