python 中條形圖繪制


一、條形圖繪制參數詳解

1、bar(left, height, width=0.8, bottom=None, color=None, edgecolor=None, linewidth=None, tick_label=None, xerr=None, yerr=None, label = None, ecolor=None, align, log=False, **kwargs)

  • x:傳遞數值序列,指定條形圖中x軸上的刻度值
  • height:傳遞數值序列,指定條形圖y軸上的高度
  • width:指定條形圖的寬度,默認為0.8
  • bottom:用於繪制堆疊條形圖
  • color:指定條形圖的填充色
  • edgecolor:指定條形圖的邊框色
  • linewidth:指定條形圖邊框的寬度,如果指定為0,表示不繪制邊框
  • tick_label:指定條形圖的刻度標簽
  • xerr:如果參數不為None,表示在條形圖的基礎上添加誤差棒
  • yerr:參數含義同xerr
  • label:指定條形圖的標簽,一般用以添加圖例
  • ecolor:指定條形圖誤差棒的顏色align:指定x軸刻度標簽的對齊方式,默認為center,表示刻度標簽居中對齊,如果設置為edge,則表示在每個條形的左下角呈現刻度標簽
  • log:bool類型參數,是否對坐標軸進行log變換,默認為False
  • **kwargs:關鍵字參數,用於對條形圖進行其他設置,如透明度等
 1 # 條形圖的繪制--垂直條形圖
 2 # 讀入數據
 3 GDP = pd.read_excel('Province GDP 2017.xlsx')
 4 '''
 5 Province    GDP
 6 北京    2.8
 7 上海    3.01
 8 廣東    8.99
 9 江蘇    8.59
10 重慶    1.95
11 天津    1.86
12 '''
13 # 設置繪圖風格(不妨使用R語言中的ggplot2風格)
14 plt.style.use('ggplot')
15 # 繪制條形圖
16 plt.bar(x = range(GDP.shape[0]), # 指定條形圖x軸的刻度值
17         height = GDP.GDP, # 指定條形圖y軸的數值
18         tick_label = GDP.Province, # 指定條形圖x軸的刻度標簽
19         color = 'steelblue', # 指定條形圖的填充色
20         width = 0.8
21        )
22 # 添加y軸的標簽
23 plt.ylabel('GDP(萬億)')
24 # 添加條形圖的標題
25 plt.title('2017年度6個省份GDP分布')
26 # 為每個條形圖添加數值標簽
27 for x,y in enumerate(GDP.GDP):
28     plt.text(x,y+0.1,'%s' %round(y,1),ha='center')
29 # 顯示圖形    
30 plt.show()

 

 ②https://matplotlib.org/api/_as_gen/matplotlib.pyplot.barh.html

 1 # 條形圖的繪制--水平條形圖
 2 # 對讀入的數據作升序排序
 3 GDP.sort_values(by = 'GDP', inplace = True)
 4 # 繪制條形圖
 5 plt.barh(y = range(GDP.shape[0]), # 指定條形圖y軸的刻度值
 6         width = GDP.GDP, # 指定條形圖x軸的數值
 7         tick_label = GDP.Province, # 指定條形圖y軸的刻度標簽
 8         color = 'steelblue', # 指定條形圖的填充色
 9        )
10 # 添加x軸的標簽
11 plt.xlabel('GDP(萬億)')
12 # 添加條形圖的標題
13 plt.title('2017年度6個省份GDP分布')
14 # 為每個條形圖添加數值標簽
15 for y,x in enumerate(GDP.GDP):
16     plt.text(x+0.1,y,'%s' %round(x,1),va='center')
17 # 顯示圖形    
18 plt.show()

  

 ③繪制堆疊條形圖

 1 import pandas as pd
 2 import matplotlib.pyplot as plt
 3 # 條形圖的繪制--堆疊條形圖
 4 # 讀入數據
 5 Industry_GDP = pd.read_excel('Industry_GDP.xlsx')
 6 # 取出四個不同的季度標簽,用作堆疊條形圖x軸的刻度標簽
 7 Quarters = Industry_GDP.Quarter.unique()
 8 # 取出第一產業的四季度值
 9 Industry1 = Industry_GDP.GPD[Industry_GDP.Industry_Type == '第一產業']
10 # 重新設置行索引
11 Industry1.index = range(len(Quarters))
12 # 取出第二產業的四季度值
13 Industry2 = Industry_GDP.GPD[Industry_GDP.Industry_Type == '第二產業']
14 # 重新設置行索引
15 Industry2.index = range(len(Quarters))
16 # 取出第三產業的四季度值
17 Industry3 = Industry_GDP.GPD[Industry_GDP.Industry_Type == '第三產業']
18 
19 # 繪制堆疊條形圖
20 # 中文亂碼和坐標軸負號的處理
21 plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
22 plt.rcParams['axes.unicode_minus'] = False
23 # 各季度下第一產業的條形圖
24 plt.bar(x = range(len(Quarters)), height=Industry1, color = 'steelblue', label = '第一產業', tick_label = Quarters)
25 # 各季度下第二產業的條形圖
26 plt.bar(x = range(len(Quarters)), height=Industry2, bottom = Industry1, color = 'green', label = '第二產業')
27 # 各季度下第三產業的條形圖
28 plt.bar(x = range(len(Quarters)), height=Industry3, bottom = Industry1  + Industry2, color = 'red', label = '第三產業')
29 # 添加y軸標簽
30 plt.ylabel('生成總值(億)')
31 # 添加圖形標題
32 plt.title('2017年各季度三產業總值')
33 # 顯示各產業的圖例
34 plt.legend(loc =2,fontsize = 'small')
35 # 顯示圖形
36 plt.show()

   

 ④水平交錯條形圖

 1 # 條形圖的繪制--水平交錯條形圖
 2 # 導入第三方模塊
 3 import matplotlib.pyplot as plt
 4 import numpy as np
 5 import pandas as pd
 6 # 讀入數據
 7 HuRun = pd.read_excel('HuRun.xlsx')
 8 # 取出城市名稱
 9 Cities = HuRun.City.unique()
10 # 取出2016年各城市億萬資產家庭數
11 Counts2016 = HuRun.Counts[HuRun.Year == 2016]
12 # 取出2017年各城市億萬資產家庭數
13 Counts2017 = HuRun.Counts[HuRun.Year == 2017]
14 
15 # 繪制水平交錯條形圖
16 bar_width = 0.4
17 plt.bar(x = np.arange(len(Cities)), height = Counts2016, label = '2016', color = 'steelblue', width = bar_width)
18 plt.bar(x = np.arange(len(Cities))+bar_width, height = Counts2017, label = '2017', color = 'indianred', width = bar_width)
19 # 添加刻度標簽(向右偏移0.225)
20 plt.xticks(np.arange(5)+0.2, Cities)
21 # 添加y軸標簽
22 plt.ylabel('億萬資產家庭數')
23 # 添加圖形標題
24 plt.title('近兩年5個城市億萬資產家庭數比較')
25 # 添加圖例
26 plt.legend()
27 # 顯示圖形
28 plt.show()

   

 二、

 1 # Pandas模塊之垂直或水平條形圖
 2 # 讀入數據
 3 GDP = pd.read_excel('Province GDP 2017.xlsx')
 4 # 繪圖(此時的數據集在前文已經按各省GDP做過升序處理)
 5 GDP.GDP.plot(kind = 'bar', width = 0.8, rot = 0, color = 'steelblue', title = '2017年度6個省份GDP分布')
 6 # 添加y軸標簽
 7 plt.ylabel('GDP(萬億)')
 8 # 添加x軸刻度標簽
 9 plt.xticks(range(len(GDP.Province)), #指定刻度標簽的位置  
10            GDP.Province # 指出具體的刻度標簽值
11           )
12 # 為每個條形圖添加數值標簽
13 for x,y in enumerate(GDP.GDP):
14     plt.text(x-0.1,y+0.2,'%s' %round(y,1),va='center')
15 # 顯示圖形
16 plt.show()

 ②

 1 # Pandas模塊之水平交錯條形圖
 2 HuRun = pd.read_excel('HuRun.xlsx')
 3 HuRun_reshape = HuRun.pivot_table(index = 'City', columns='Year', values='Counts').reset_index()
 4 # 對數據集降序排序
 5 HuRun_reshape.sort_values(by = 2016, ascending = False, inplace = True)
 6 HuRun_reshape.plot(x = 'City', y = [2016,2017], kind = 'bar', color = ['steelblue', 'indianred'], 
 7                    rot = 0, # 用於旋轉x軸刻度標簽的角度,0表示水平顯示刻度標簽
 8                    width = 0.8, title = '近兩年5個城市億萬資產家庭數比較')
 9 # 添加y軸標簽
10 plt.ylabel('億萬資產家庭數')
11 plt.xlabel('')
12 plt.show()

 ③

 1 # seaborn模塊之垂直或水平條形圖
 2 # 導入第三方模塊
 3 import seaborn as sns
 4 
 5 # 讀入數據
 6 GDP = pd.read_excel('Province GDP 2017.xlsx')
 7 sns.barplot(y = 'Province', # 指定條形圖x軸的數據
 8             x = 'GDP', # 指定條形圖y軸的數據
 9             data = GDP, # 指定需要繪圖的數據集
10             color = 'steelblue', # 指定條形圖的填充色
11             orient = 'horizontal' # 將條形圖水平顯示
12            )
13 # 重新設置x軸和y軸的標簽
14 plt.xlabel('GDP(萬億)')
15 plt.ylabel('')
16 # 添加圖形的標題
17 plt.title('2017年度6個省份GDP分布')
18 # 為每個條形圖添加數值標簽
19 for y,x in enumerate(GDP.GDP):
20     plt.text(x,y,'%s' %round(x,1),va='center')
21 # 顯示圖形
22 plt.show()

 ④

 1 # 讀入數據
 2 Titanic = pd.read_csv('titanic_train.csv')
 3 # 繪制水平交錯條形圖
 4 sns.barplot(x = 'Pclass', # 指定x軸數據
 5             y = 'Age', # 指定y軸數據
 6             hue = 'Sex', # 指定分組數據
 7             data = Titanic, # 指定繪圖數據集
 8             palette = 'RdBu', # 指定男女性別的不同顏色
 9             errcolor = 'blue', # 指定誤差棒的顏色
10             errwidth=2, # 指定誤差棒的線寬
11             saturation = 1, # 指定顏色的透明度,這里設置為無透明度
12             capsize = 0.05 # 指定誤差棒兩端線條的寬度
13            )
14 # 添加圖形標題
15 plt.title('各船艙等級中男女乘客的年齡差異')
16 # 顯示圖形
17 plt.show()

     


免責聲明!

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



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