條狀圖基本使用
條狀圖也是非常常用的一種圖表類型.
繪制條狀圖, 我們用到函數:
pandas.pyplot.bar(): 繪制垂直條狀圖. pandas.pyplot.barh(): 繪制水平條狀圖.
條形圖是統計圖資料分析中最常用的圖形。主要特點有:
- 1、能夠使人們一眼看出各個各個項目數據的大小。
- 2、易於比較各個不同項目數據之間的差別。
基本使用
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame from matplotlib.font_manager import FontProperties b1 = plt.bar([1, 2, 3, 4], [4, 5, 6, 7], width=0.3) b2 = plt.bar([1+0.3, 2+0.3, 3+0.3, 4+0.3], [7, 3, 2, 9], width=0.3) # plt.bar([1, 2, 3, 4], [4, 5, 6, 7], bottom=[4, 5, 6, 7], width=0.3) plt.xlim(0, 5) plt.xticks([1.15, 2.15, 3.15, 4.15], [1, 2, 3, 4]) plt.grid(True) print(type(b1)) plt.legend((b1, b2), ('hehe', 'haha')) plt.show()
plt.barh([1, 2, 3, 4, 5], [2, 3, 4, 5, 6], height=0.3) plt.show()
條狀圖案例
數據截圖:
數據來源: https://www.kaggle.com/START-UMD/gtd 數據共170273行35列. 包括全世界從1970年-2016年期間所有國家發生的恐怖襲擊事件信息.
完成任務:
- 計算世界各國總共發生的恐怖襲擊事件總數和實際發生的恐怖襲擊事件總數. 並計算發生恐怖襲擊事件最多的前10個國家, 並通過條狀圖展示數據信息.
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame from matplotlib.font_manager import FontProperties data = pd.read_csv('1970-2016世界恐怖襲擊數據-utf8.csv', dtype=np.str, usecols=['country', 'success']) # 替換NaN值 data.fillna('0', inplace=True) # 處理success列中非0 非1值 def fix_value(col): if col.name == 'success': col = np.where(col == '1', col, np.where(col == '0', col, '0')) return col data = data.apply(fix_value) data[:10]
data_by_group = data.groupby('country') # 統計每一組數據的條數 all_data = data_by_group.count() # 成功恐怖襲擊的次數 def caculate_success(group_data): # 先對當前這一組的元素轉換為數字類型,並求總和 group_data = group_data.astype(np.int32).sum() return group_data # 成功恐怖襲擊次數國家 suc_data = data_by_group.apply(caculate_success) # 恐怖襲擊次數最多的前10個國家 many_country_list = all_data.sort_values('success')[-10:][::-1] # many_suc_list = suc_data[many_country_list.index]
many_suc_list = suc_data.loc[many_country_list.index] # 合並兩個結果 result = pd.concat([many_country_list, many_suc_list], axis=1) result.columns = ['all', 'suc'] result
plt.figure(figsize=(16, 9)) plt.bar([x for x in range(10)], result['all']) plt.xticks([x for x in range(10)], result.index) plt.grid(True) for a, b in enumerate(result['all']): plt.text(a-0.2, b+300, str(b), fontsize=15) plt.legend(['times']) plt.show()