可视化数据python_Python数据可视化

Matplotlib模块

1. 离散型数据的可视化

1.1饼图

# 导入第三方模块

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

# 构造数据

edu = [0.2515,0.3724,0.3336,0.0368,0.0057]

labels = ['中专','大专','本科','硕士','其他']

explode = [0,0.1,0,0,0]

# 绘制饼图

plt.pie(x = edu, # 绘图数据

labels=labels, # 添加教育水平标签

autopct='%.1f%%', # 设置百分比的格式,这里保留一位小数

explode = explode

)

#plt.axes(aspect='equal')

# 显示图形

plt.show()

1.2条形图

import pandas as pd

# 读入数据

GDP = pd.read_excel(r'Province GDP 2017.xlsx')

GDP

# 设置绘图风格(不妨使用R语言中的ggplot2风格)

plt.style.use('ggplot')

# 绘制条形图

plt.bar(x = range(GDP.shape[0]), # 指定条形图x轴的刻度值

height = GDP.GDP, # 指定条形图y轴的数值

tick_label = GDP.Province, # 指定条形图x轴的刻度标签

color = 'steelblue', # 指定条形图的填充色

)

# 添加y轴的标签

plt.ylabel('GDP(万亿)')

# 添加条形图的标题

plt.title('2017年度6个省份GDP分布')

# 为每个条形图添加数值标签

for x,y in enumerate(GDP.GDP):

plt.text(x,y+0.1,'%s' %round(y,1),ha='center')

# 显示图形

plt.show()

# 对读入的数据做升序排序

GDP.sort_values(by = 'GDP', inplace = True)

# 绘制条形图

plt.barh(y = range(GDP.shape[0]), # 指定条形图y轴的刻度值

width = GDP.GDP, # 指定条形图x轴的数值

tick_label = GDP.Province, # 指定条形图y轴的刻度标签

color = 'steelblue', # 指定条形图的填充色

)

# 添加x轴的标签

plt.xlabel('GDP(万亿)')

# 添加条形图的标题

plt.title('2017年度6个省份GDP分布')

# 为每个条形图添加数值标签

for y,x in enumerate(GDP.GDP):

plt.text(x+0.1,y,'%s' %round(x,1),va='center')

# 显示图形

plt.show()

HuRun = pd.read_excel('HuRun.xlsx')

# Pandas模块之水平交错条形图

HuRun_reshape = HuRun.pivot_table(index = 'City', columns='Year',

values='Counts').reset_index()

# 对数据集降序排序

HuRun_reshape.sort_values(by = 2016, ascending = False, inplace = True)

HuRun_reshape.plot(x = 'City', y = [2016,2017], kind = 'bar',

color = ['steelblue', 'indianred'],

# 用于旋转x轴刻度标签的角度,0表示水平显示刻度标签

rot = 0,

width = 0.8, title = '近两年5个城市亿万资产家庭数比较')

# 添加y轴标签

plt.ylabel('亿万资产家庭数')

plt.xlabel('')

plt.show()

2. 连续性数据的可视化

2.1直方图

Titanic = pd.read_csv('titanic_train.csv')

# 检查年龄是否有缺失(如果数据中存在缺失值,将无法绘制直方图)

any(Titanic.Age.isnull())

# 不妨删除含有缺失年龄的观察

Titanic.dropna(subset=['Age'], inplace=True)

# 绘制直方图

plt.hist(x = Titanic.Age, # 指定绘图数据

bins = 20, # 指定直方图中条块的个数

color = 'steelblue', # 指定直方图的填充色

edgecolor = 'black' # 指定直方图的边框色

)

# 添加x轴和y轴标签

plt.xlabel('年龄')

plt.ylabel('频数')

# 添加标题

plt.title('乘客年龄分布')

# 显示图形

plt.show()

2.2箱线图

Sec_Buildings = pd.read_excel('sec_buildings.xlsx')

# 绘制箱线图

plt.boxplot(x = Sec_Buildings.price_unit, # 指定绘图数据

patch_artist=True, # 要求用自定义颜色填充盒形图,默认白色填充

showmeans=True, # 以点的形式显示均值

boxprops = {'color':'black','facecolor':'steelblue'},# 设置箱体属性,如边框色和填充色

# 设置异常点属性,如点的形状、填充色和点的大小

flierprops = {'marker':'o','markerfacecolor':'red', 'markersize':3,'markeredgecolor':'red'},

# 设置均值点的属性,如点的形状、填充色和点的大小

meanprops = {'marker':'D','markerfacecolor':'indianred', 'markersize':4},

# 设置中位数线的属性,如线的类型和颜色

medianprops = {'linestyle':'--','color':'orange'},

labels = [''] # 删除x轴的刻度标签,否则图形显示刻度标签为1

)

# 添加图形标题

plt.title('二手房单价分布的箱线图')

# 显示图形

plt.show()

2.3折线图marker

%matplotlib

# 数据读取

wechat = pd.read_excel(r'wechat.xlsx')

# 绘制单条折线图

plt.plot(wechat.Date, # x轴数据

wechat.Counts, # y轴数据

linestyle = '-', # 折线类型

linewidth = 2, # 折线宽度

color = 'steelblue', # 折线颜色

marker = 'o', # 折线图中添加圆点

markersize = 6, # 点的大小

markeredgecolor='black', # 点的边框色

markerfacecolor='brown') # 点的填充色

# 获取图的坐标信息

ax = plt.gca()

# 设置日期的显示格式

date_format = mpl.dates.DateFormatter("%m-%d")

ax.xaxis.set_major_formatter(date_format)

# 设置x轴每个刻度的间隔天数

xlocator = mpl.ticker.MultipleLocator(7)

ax.xaxis.set_major_locator(xlocator)

# 添加y轴标签

plt.ylabel('人数')

# 添加图形标题

plt.title('每天微信文章阅读人数趋势')

# 显示图形

plt.show()

3. 关系型数据的可视化

3.1散点图

# 读入数据

iris = pd.read_csv(r'iris.csv')

# 绘制散点图

plt.scatter(x = iris.Petal_Width, # 指定散点图的x轴数据

y = iris.Petal_Length, # 指定散点图的y轴数据

color = 'steelblue' # 指定散点图中点的颜色

)

# 添加x轴和y轴标签

plt.xlabel('花瓣宽度')

plt.ylabel('花瓣长度')

# 添加标题

plt.title('鸢尾花的花瓣宽度与长度关系')

# 显示图形

plt.show()

3.2热力图

import numpy as np

import seaborn as sns

# 读取数据

Sales = pd.read_excel(r'Sales.xlsx')

# 根据交易日期,衍生出年份和月份字段

Sales['year'] = Sales.Date.dt.year

Sales['month'] = Sales.Date.dt.month

# 统计每年各月份的销售总额(绘制热力图之前,必须将数据转换为交叉表形式)

Summary = Sales.pivot_table(index = 'month', columns = 'year', values = 'Sales', aggfunc = np.sum)

Summary

# 绘制热力图

sns.heatmap(data = Summary, # 指定绘图数据

cmap = 'PuBuGn', # 指定填充色

linewidths = .1, # 设置每个单元格边框的宽度

annot = True, # 显示数值

fmt = '.1e' # 以科学计算法显示数据

)

#添加标题

plt.title('每年各月份销售总额热力图')

# 显示图形

plt.show()

4. 多图形的组合

# 设置大图框的长和高

plt.figure(figsize = (12,6))

# 设置第一个子图的布局

ax1 = plt.subplot2grid(shape = (2,3), loc = (0,0))

# 设置第二个子图的布局

ax2 = plt.subplot2grid(shape = (2,3), loc = (0,1))

# 设置第三个子图的布局

ax3 = plt.subplot2grid(shape = (2,3), loc = (0,2), rowspan = 2)

# 设置第四个子图的布局

ax4 = plt.subplot2grid(shape = (2,3), loc = (1,0), colspan = 2)

fig=plt.figure(1)

ax1=plt.subplot(2,1,1) #两行一列的画纸,选中画纸1作图

plt.plot([1,2,3,4])

ax2=plt.subplot(2,1,2) #两行一列的画纸,选中画纸2作图

plt.plot([5,6,7,8])

plt.show()

5.绘制多条线

import numpy as np

t = np.arange(0, 5, 0.2)

x1=y1=t

x2=x1

y2=t**2

x3=x1

y3=t**3

linelist=plt.plot(x1,y1,x2,y2,x3,y3)

plt.setp(linelist,color='r')

plt.show()

fig=plt.figure(1)

ax1=plt.subplot(2,1,1)

plt.plot([1,2,3,4])

ax2=plt.subplot(2,1,1)

plt.plot([5,6,7,8])

plt.show()

6.注释

x=[1,2,3,4]

y=[1,4,9,16]

plt.plot(x,y)

plt.xlabel('x坐标轴')

plt.ylabel('y坐标轴')

plt.title('title')

plt.annotate('我是注释',xy=(2,4), xytext=(2,9), arrowprops=dict(facecolor='black', shrink=0.1))

plt.show()

pandas模块

ax1

Df.plot(x='',y='',kind='',label='',ax=ax1,color='')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值