Matplotlib中柱狀圖bar使用


一、函數原型

matplotlib.pyplot.bar(left, height, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3)

 1. left:x軸的位置序列,一般采用range函數產生一個序列,但是有時候可以是字符串

 2. height:y軸的數值序列,也就是柱形圖的高度,一般就是我們需要展示的數據;

 3. alpha:透明度,值越小越透明

 4. width:為柱形圖的寬度,一般這是為0.8即可;

 5. color或facecolor:柱形圖填充的顏色;

 6. edgecolor:圖形邊緣顏色

 7. label:解釋每個圖像代表的含義,這個參數是為legend()函數做鋪墊的,表示該次bar的標簽,其中legend()函數loc參數如下:

'best'         : 0, (only implemented for axes legends)(自適應方式)
'upper right'  : 1,
'upper left'   : 2,
'lower left'   : 3,
'lower right'  : 4,
'right'        : 5,
'center left'  : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center'       : 10,

 

 8. linewidth or linewidths or lw:邊緣or線的寬

import pandas as pd
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] 

import matplotlib.pyplot as plt
y = range(1,17)

plt.bar(np.arange(16), y, alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=3)
plt.bar(np.arange(16)+0.4, y, alpha=0.2, width=0.3, color='green', edgecolor='blue', label='The Second Bar', lw=3)
plt.legend(loc='upper left')
plt.show()

  

 1)為坐標軸加上標簽

plt.xlabel('This Is X Axis', fontsize=15)
plt.ylabel('This Is Y Axis', fontsize=15)
plt.title('This Is My Title', fontsize=15)
#fontsize可以控制字體大小

  2)X軸可以是字符串

import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] 

import matplotlib.pyplot as plt

x = ['c', 'a', 'd', 'b']
y = [1, 2, 3, 4]

plt.bar(x, y, alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=3)
plt.legend(loc='upper left')

plt.show()

 python3已經自動將x軸的字符串進行了排序,x軸變成了[ 'a', 'b', 'c', 'd' ](放心:同時x軸對應的y軸值也跟隨x的順序變化),python2並未自動對x軸字符串進行排序:

 

 3) 如果想自己給x軸的bar加上標簽,或者想讓標簽傾斜:plt.xticks()

import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] 

import matplotlib.pyplot as plt

x = []
y = []

x = ['c', 'a', 'd', 'b']
y = [1, 2, 3, 4]
#plt.figure(figsize=(40,40))
plt.bar(x, y, alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=3)
plt.legend(loc='upper left')
plt.xticks(np.arange(4), ('A','B', 'C', 'D'), rotation=30)#rotation控制傾斜角度

plt.show()

 4) 如果想控制y軸數值間隔:plt.yticks(np.arange(0,5,0.2))

import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] 

import matplotlib.pyplot as plt

x = []
y = []

x = ['c', 'a', 'd', 'b']
y = [1, 2, 3, 4]
#plt.figure(figsize=(40,40))
plt.bar(x, y, alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=3)
plt.legend(loc='upper left')
plt.xticks(np.arange(4), ('A','B', 'C', 'D'), rotation=30)#rotation控制傾斜角度
plt.yticks(np.arange(0, 5, 0.2))
plt.show()

  5)加上label和title

import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] 

import matplotlib.pyplot as plt

x = ['c', 'a', 'd', 'b']
y = [1, 2, 3, 4]
#plt.figure(figsize=(40,40))
plt.bar(x, y, alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=3)
plt.legend(loc='upper left')
plt.xticks(np.arange(4), ('A','B', 'C', 'D'), rotation=30)#rotation控制傾斜角度
plt.yticks(np.arange(0, 5, 0.4))

#fontsize控制了label和title字體大小
plt.ylabel('Missing Rate(%)', fontsize=10)
plt.title('Missing Rate Of Attributes', fontsize=10)
plt.xlabel('圖1. 屬性缺失比率', fontsize=10)

#但是如果想調整軸上數值字體大小呢?
plt.tick_params(axis='both', labelsize=15)

plt.show()

  

 6)如果遇到title越出畫布的,可以使用plt.figure(figsize=(50,80))適當調整figsize的大小,plt.savefig('NA.png')可以保存圖片。

 7)可以將圖形框的四條邊去掉,或者坐標軸線寬進行加粗

import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] 

import matplotlib.pyplot as plt

x = ['c', 'a', 'd', 'b']
y = [1, 2, 3, 4]

plt.figure(figsize=(40,40), dpi=80)

#底部和左邊加粗,頂部和右邊消失
ax = plt.subplot(1,1,1)
ax.spines['bottom'].set_linewidth(10)
ax.spines['left'].set_linewidth(10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.bar(x, y, alpha=0.8, width=0.3, color='yellow', edgecolor='red', label='The First Bar', lw=6)
plt.legend(loc='upper left', fontsize=35)

plt.xticks(np.arange(4), ('A','B', 'C', 'D'), rotation=30)#rotation控制傾斜角度
plt.yticks(np.arange(0, 5, 0.4))

#fontsize控制了label和title字體大小
plt.ylabel('Missing Rate(%)', fontsize=40)
plt.title('Missing Rate Of Attributes', fontsize=40)
plt.xlabel('圖1. 屬性缺失比率', fontsize=40)

#但是如果想調整軸上數值字體大小呢?
plt.tick_params(axis='both', labelsize=35)

plt.savefig('NA.png', dpi=80)

 8)給柱狀圖頂部添加文字(plt.text)

"""
    默認的是豎值條形圖
"""
import numpy as np
import matplotlib.pyplot as plt

# 將全局的字體設置為黑體
plt.rcParams['font.family'] = 'SimHei'

# 數據
N = 5
y = [20, 10, 30, 25, 15]
x = np.arange(N)
# 添加地名坐標
str1 = ("北京", "上海", "武漢", "深圳", "重慶")

# 繪圖 x x軸, height 高度, 默認:color="blue", width=0.8
p1 = plt.bar(x, height=y, width=0.5, label="城市指標", tick_label=str1)

# 添加數據標簽,也就是給柱子頂部添加標簽
for a, b in zip(x, y):
    plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=10)

# 添加圖例
plt.legend()

# 展示圖形
plt.show()

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM