當前位置:
首頁 >
matplotlib 绘图-barChart
發布時間:2025/4/16
38
豆豆
生活随笔
收集整理的這篇文章主要介紹了
matplotlib 绘图-barChart
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?matplotlib 是python最著名的繪圖庫,它提供了一整套和matlab相似的命令API,十分適合交互式地進行制圖。而且也可以方便地將它作為繪圖控件,嵌入GUI應用程序中。它的文檔相當完備,并且 Gallery頁面 中有上百幅縮略圖,打開之后都有源程序。因此如果你需要繪制某種類型的圖,只需要在這個頁面中瀏覽/復制/粘貼一下,基本上都能搞定。
現在我們從最簡單的例子開始講解,
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來說明x和y軸坐標意義。
下面通過plt.xticks來說明x軸每條bar分別代表的意義,
使用align對說明的位置進行控制
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()接下來通過plt.title給繪制的圖像添加標題
最后還有就是對Y軸每條bar上添加對應值的顯示,同時添加 legend,通過plt.bar中的參數yerr設置y軸突出的長度。
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()
總結
以上是生活随笔為你收集整理的matplotlib 绘图-barChart的全部內容,希望文章能夠幫你解決所遇到的問題。