返回顶部

数据分析 Matplotlib 之条状图

条状图基本使用

条状图也是非常常用的一种图表类型.

绘制条状图, 我们用到函数:

 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()

 

 

  

posted @ 2019-10-02 22:27  Crazymagic  阅读(1887)  评论(0编辑  收藏  举报