Python数据可视化:Matplotlib 直方图、箱线图、条形图、热图、折线图、散点图。。。

介绍

      使用Python进行数据分析,数据的可视化是数据分析结果最好的展示方式,这里从Analytic Vidhya中找到的相关数据,进行一系列图形的展示,从中得到更多的经验。
      强烈推荐:Analytic Vidhya

Python数据可视化库

  • Matplotlib:其能够支持所有的2D作图和部分3D作图。能通过交互环境做出印刷质量的图像。
  • Seaborn:基于Matplotlib,seaborn提供许多功能,比如:内置主题、颜色调色板、函数和提供可视化单变量、双变量、线性回归的工具。其能帮助我们构建复杂的可视化。

数据集

EMPIDGenderAgeSalesBMIIncome
E001M34123Normal350
E002F40114Overweight450
E003F37135Obesity169
E004M30139Underweight189
E005F44117Underweight183
E006M36121Normal80
E007M32133Obesity166
E008F26140Normal120
E009M32133Normal75
E010M36133Underweight40

作图

# -*- coding:UTF-8 -*-

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

# 0、导入数据集
df = pd.read_excel('first.xlsx', 'Sheet1')
# 1、直方图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(df['Age'], bins=7)
plt.title('Age distribution')
plt.xlabel('Age')
plt.ylabel('Employee')
plt.show()

这里写图片描述

# 2、箱线图  
fig = plt.figure()
ax = fig.add_subplot(111)
ax.boxplot(df['Age'])
plt.show()

这里写图片描述

# 3、小提琴图
sns.violinplot(df['Age'], df['Gender'])
sns.despine()
plt.show()

这里写图片描述

# 4、条形图
var = df.groupby('Gender').Sales.sum()
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel('Gender')
ax1.set_ylabel('Sum of Sales')
ax1.set_title('Gender wise Sum of Sales')
var.plot(kind='bar')
plt.show()

这里写图片描述

# 5、折线图
var = df.groupby('BMI').Sales.sum()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('BMI')
ax.set_ylabel('Sum of Sales')
ax.set_title('BMI wise Sum of Sales')
var.plot(kind='line')
plt.show()

这里写图片描述

# 6、堆积柱形图
var = df.groupby(['BMI', 'Gender']).Sales.sum()
var.unstack().plot(kind='bar', stacked=True, color=['red', 'blue'])
plt.show()

这里写图片描述

# 7、散点图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(df['Age'], df['Sales'])
plt.show()

这里写图片描述

# 8、气泡图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(df['Age'], df['Sales'], s=df['Income'])  # 第三个变量表明根据收入气泡的大小
plt.show()

这里写图片描述

# 9、饼图
var = df.groupby(['Gender']).sum().stack()
temp = var.unstack()
type(temp)
x_list = temp['Sales']
label_list = temp.index
plt.axis('equal')
plt.pie(x_list, labels=label_list, autopct='%1.1f%%')
plt.title('expense')
plt.show()

这里写图片描述

# 10、热图
data = np.random.rand(4, 2)
rows = list('1234')
columns = list('MF')
fig, ax = plt.subplots()
ax.pcolor(data, cmap=plt.cm.Reds, edgecolor='k')
ax.set_xticks(np.arange(0, 2)+0.5)
ax.set_yticks(np.arange(0, 4)+0.5)
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
ax.set_xticklabels(columns, minor=False, fontsize=20)
ax.set_yticklabels(rows, minor=False, fontsize=20)
plt.show()

这里写图片描述

  • 49
    点赞
  • 391
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值