Python数据分析(一)matplotlib

数据分析是把大量的数据进行统计和整理,得出结论,为后续的决策提供数据支持。


Matplotlib

matplotlib是最流行的Python底层绘图库,主要工作为数据可视化图表,仿照MATLAB构建。能将数据进行可视化,更直观的呈现;是数据更加客观、更具说服力。

matplotlib实例

(1)将坐标点连接成一条线,组成一个折线图
假设一天中每隔两小时(range(2,26,2))的气温(℃)分别为[15,13,14.5,17,20,25,26,26,27,22,18,15]

from matplotlib import pyplot as plt
x = range(2,26,2)	# 数据在x轴的位置,是一个可迭代对象
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]	# 数据在y轴的位置,是一个可迭代对象,x轴和y轴的数据一起组成了所要绘制出的坐标
plt.plot(x,y)		# 传入x和y,通过plot绘制出折线图
plt.show()			# 显示图形

绘制的图片
在这里插入图片描述
存在的问题:
①设置图片大小
②保存图片
③描述信息,例如x轴和y轴表示的信息,图表示的信息
④调整x或者y的刻度的间距
⑤线条的样式(例如颜色、透明度等)
⑥标记出特殊的点(例如最高、最低点)
⑦给图片添加水印

设置图片大小

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20,8),dpi=80)	# 绘制宽20高8的图片。dpi指每英寸上点的个数,在图像模糊的时候传入dpi参数,让图片更清晰
x = range(2,26,2)	
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]	

plt.plot(x,y)	
plt.savefig("./sig_size.png")	# 保存图片,可以保存为svg矢量图格式,放大不会有锯齿
plt.show()

设置x轴的刻度
从图中可以看到,x轴每隔5个单位距离标出,可以手动指定x轴。

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20,8),dpi=80)	# 绘制宽20高8的图片。dpi指每英寸上点的个数,在图像模糊的时候传入dpi参数,让图片更清晰
x = range(2,26,2)	
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]	

plt.plot(x,y)
plt.xticks(x)	# 设置x轴的刻度	
plt.savefig("./sig_size.png")	# 保存图片,可以保存为svg矢量图格式,放大不会有锯齿
plt.show()

在这里插入图片描述
①将传入x的每个值都绘制到x轴上
②隔步长1画点
将“plt.xticks(x)”换成“plt.xticks(range(2,25))”即可
在这里插入图片描述
③改变x轴的精度

plt.xticks(range(2,25,3))	# 稀疏

由于range中不能传入小数,所以为了提高x轴的精度,可以通过自己建立一个列表

_xtick_labels = [i/2 for i in range(4,49)]
plt.xticks(_xtick_labels)

或是使用numpy

import numpy as np
plt.xticks(np.arange(2,24.5,0.5))

在这里插入图片描述
提高精度的情况下,采用取步长操作降低刻度的密度

_xtick_labels = [i/2 for i in range(4,49)]
plt.xticks(_xtick_labels[::3])

import numpy as np
_xtick_labels=np.arange(2,24.5,0.5)
plt.xticks(_xtick_labels[::3])

在这里插入图片描述
④y轴同理

plt.yticks(range(min(y),max(y)+1))

在这里插入图片描述
(2)列表a表示10点到12点的每一分钟的气温,如何绘制折线图观察每分钟气温的变化情况。

# 随机数初始化气温数据
a = [random.randint(20,35) for i in range(120)]
import matplotlib.pyplot as plt
import random

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize=(20,8),dpi=80)

plt.plot(x,y)	

plt.show()

在这里插入图片描述
①调整x轴的刻度,要求x轴刻度为指定内容

# 方法一
import matplotlib.pyplot as plt
import random

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize=(20,8),dpi=80)

plt.plot(x,y)	
plt.rcParams['font.sans-serif'] = ['SimHei']    # 用于正常显示中文标签
# matplotlib默认不显示中文

_x = list(x)
_xtick_labels = ["10点{}分".format(i) for i in range(60)] 
# python2.6开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
# 基本语法是通过 {} 和 : 来代替以前的 % 
# format 函数可以接受不限个参数,位置可以不按顺序。
_xtick_labels += ["11点{}分".format(i-60) for i in range(60,120)]     
# 为了方便理解使用range(60,120),再将i-60。实际可以直接使用range(60)


plt.xticks(_x[::3], _xtick_labels[::3],rotation=-45)    # ratation是旋转度数,度数可为负
# 取步长,数字和字符串一一对应,数据的长度一样
plt.show()
# 方法二
import matplotlib.pyplot as plt
import random
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname=r"C:/Windows/Fonts/simsun.ttc")

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize=(20,8),dpi=80)
plt.plot(x,y)	
# plt.rcParams['font.sans-serif'] = ['SimHei']    # 用于正常显示中文标签
# matplotlib默认不显示中文

_x = list(x)
_xtick_labels = ["10点{}分".format(i) for i in range(60)] 
# python2.6开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
# 基本语法是通过 {} 和 : 来代替以前的 % 
# format 函数可以接受不限个参数,位置可以不按顺序。
_xtick_labels += ["11点{}分".format(i-60) for i in range(60,120)]     
# 为了方便理解使用range(60,120),再将i-60。实际可以直接使用range(60)


plt.xticks(_x[::3], _xtick_labels[::3],rotation=-45, FontProperties=my_font)    # ratation是旋转度数,度数可为负
# 取步长,数字和字符串一一对应,数据的长度一样
plt.show()

几种显示中文字体的方式
方法一设置的是全局字体,方法二只设置了x轴的字体
当增加x轴、y轴的描述信息和图表标题时也分两种情况

# 方法一对应情况
# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度 单位(℃)")
plt.title("10点到12点每分钟的气温变化情况")
# 方法二对应情况
# 添加描述信息
plt.xlabel("时间", FontProperties=my_font)
plt.ylabel("温度 单位(℃)", FontProperties=my_font)
plt.title("10点到12点每分钟的气温变化情况", FontProperties=my_font)

在这里插入图片描述

plt.rcParams[]参数

# 拓展
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
常见字体名对应英文名称
宋体SimSun
黑体SimHei
微软雅黑Microsoft YaHei
微软正黑体Microsoft JhengHei
新宋体NSimSun
新细明体PMingLiU
细明体MingLiU
标楷体DFKai-SB
仿宋FangSong
楷体KaiTi
隶书LiSu
幼圆YouYuan
华文细黑STXihei
华文楷体STKaiti
华文宋体STSong
华文中宋STZhongsong
华文仿宋STFangsong
方正舒体FZShuTi
方正姚体FZYaoti
华文彩云STCaiyun
华文琥珀STHupo
华文隶书STLiti
华文行楷STXingkai
华文新魏STXinwei

②绘制网格

plt.grid()
# 默认横线数量为y轴刻度数量,竖线数量为x轴刻度数量

在这里插入图片描述
网格的密集程度取决于x轴和y轴刻度的密集程度。
设置网格透明度

plt.grid(alpha=0.4)

(3)将两条折线图绘制到一张图表中

import matplotlib.pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname=r"C:/Windows/Fonts/simsun.ttc")

y_1 = [1,0,1,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1,2,1,2,1,1,1,1,1,1,1,1]
x = range(11,31)

plt.figure(figsize=(20,8),dpi=80)
plt.plot(x,y_1)
plt.plot(x,y_2)	

_xtick_labels = ["{}岁".format(i) for i in x] 
plt.xticks(x, _xtick_labels,FontProperties=my_font)
plt.grid(alpha=0.4)
plt.show()

在这里插入图片描述
①在图形中标注折线的描述(添加图例)

import matplotlib.pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname=r"C:/Windows/Fonts/simsun.ttc")

y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1,2,1,2,1,1,1,1,1,1,1]
x = range(11,31)

plt.figure(figsize=(20,8),dpi=80)
plt.plot(x,y_1,label="a")
plt.plot(x,y_2,label="b")	

_xtick_labels = ["{}岁".format(i) for i in x] 
plt.xticks(x, _xtick_labels,FontProperties=my_font)
plt.grid(alpha=0.4)
# 添加图例,两折线的标注添加到图形上(图例就是告诉用户那条线表示什么)
plt.legend()
# 如果需要显示中文标注,需要在括号内添加参数“plt.legend(prop=my_font)”,注意跟别的不同这里的参数为prop
plt.show()

②调整图例位置

plt.legend(prop=my_font, loc="upper left")
# 将图例调整至左上角
# 不指定时默认右上角

③自定义绘制图形的风格

plt.plot(
	x, # x
	y, # y
	# 在绘制时指定属性
	color = 'r', # 线条颜色
	linestyle = '--', # 线条风格
	linewidth = 5, # 线条粗细
	
	alpha = 0.5, # 透明度
	)
颜色字符风格字符
r 红色- 实线
g 绿色– 虚线,破折线
b 蓝色-. 点划线
w 白色: 点虚线,虚线
‘’ 留空或空格,无线条
c 青色
m 洋红
y 黄色
k 黑色
#00ff00 16进制
0.8 灰度值字符串
plt.plot(x,y_1,label="a", color="orange", linestyle=':')
plt.plot(x,y_2,label="b", color="cyan", linestyle='-.')	

在这里插入图片描述
网格的虚线也可以指定

plt.grid(alpha=0.4, linestyle=':')

(4)阶段总结
①绘制折线图(plt.plot)
②设置图片的大小和分辨率(plt.figure)
③图片的保存(plt.savefig)
④设置x、y轴上的刻度和字符串(xticks)
⑤解决刻度稀疏和密集的问题(xticks)
⑥设置标题,x、y轴的label(title, xlabel, ylabel)
⑦字体(font_manager, fontproperties, matplotlob.rc)
⑧一个图上绘制多个图形(plt多次plot)
⑨为不同图形添加图例(label+legend)
matplotlib实例
matplotlib能够绘制折线图,散点图,柱状图,直方图,箱线图,饼图等
各统计图特点:
在这里插入图片描述
(5)绘制散点图(plt.scatter(x,y))
已有北京2016年3,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温随时间(天)变化的某种规律?

# 气温数据
a = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
b = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]
from matplotlib import pyplot as plt
from matplotlib import font_manager

y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]

x_3 = range(1,32)
x_10 = range(41, 72)
# 为了让3月和10月的数据分散开

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

# 设置图形大小
plt.figure(figsize=(25,8), dpi=80)

# 使用scatter方法绘制散点图,和之前绘制折线图的唯一区别
plt.scatter(x_3, y_3, label="3月份")
plt.scatter(x_10, y_10, label="10月份")

# 调整x轴的刻度
_x = list(x_3)+list(x_10)
_xtick_labels = ["3月{}日".format(i) for i in x_3]
_xtick_labels += ["10月{}日".format(i-40) for i in x_10]
plt.xticks(_x[::2], _xtick_labels[::2], rotation=45)

# 添加图例
plt.legend(loc="upper left")

# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("标题")

plt.show()

散点图的应用场景:
①不同条件(维度)之间的内在关联关系
②观察数据的离散聚合程度

(6)绘制条形图
已有2017年内地电影票房前20的电影(列表a)和电影票房数据(列表b),如何更直观的展示该数据。

a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊"]
b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23] #单位:亿
from matplotlib import pyplot as plt

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

a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:\n最后的骑士","摔跤吧!爸爸","加勒比海盗5:\n死无对证","金刚:骷髅岛","极限特工:\n终极回归","生化危机6:\n终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:\n殊死一战","蜘蛛侠:\n英雄归来","悟空传","银河护卫队2","情圣","新木乃伊"]
# 加“\n”换行为了使名称与条形图相对应
b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23] #单位:亿


plt.figure(figsize=(20,8), dpi=80)
# 绘制条形图
plt.bar(range(len(a)), b, width=0.3)
# 设置字符串到x轴
plt.xticks(range(len(a)), a, rotation=45)

plt.show()

在这里插入图片描述
①绘制横向条形图(barh+height)

from matplotlib import pyplot as plt
from matplotlib import font_manager

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

a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊"]
b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23] #单位:亿

plt.figure(figsize=(20,8), dpi=80)
# 绘制条形图
plt.barh(range(len(a)), b, height=0.3)
# 设置字符串到x轴
plt.yticks(range(len(a)), a)

plt.grid(alpha=0.3)

plt.show()

在这里插入图片描述
②已知列表a中电影分别在2017-09-14(b_14),2017-09-15(b_15),2017-09-16(b_16)三天的票房,为了展示列表中电影本身的票房以及同其他电影的数据对比情况,应该如何更加直观的呈现该数据。

# 数据
a = ["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b_16 = [15746,312,4497,319]
b_15 = [12357,156,2045,168]
b_14 = [2358,399,2358,362]
from matplotlib import pyplot as plt
from matplotlib import font_manager

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

a = ["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b_16 = [15746,312,4497,319]
b_15 = [12357,156,2045,168]
b_14 = [2358,399,2358,362]

bar_width = 0.2

x_14 = list(range(len(a)))
x_15 = [i+0.2 for i in x_14]
x_16 = [i+0.2*2 for i in x_14]

plt.figure(figsize=(20,8),dpi=80)

plt.bar(range(len(a)), b_14, width=bar_width, label="14日")
plt.bar(x_15, b_15, width=bar_width, label="15日")
plt.bar(x_16, b_16, width=bar_width, label="16日")

# 设置x轴的刻度
plt.xticks(x_15,a)

plt.legend()

plt.show()

(7)绘制直方图
已有250部电影的时长(列表a中),希望统计出这些电影时长的分布状态(比如时长为100分钟到120分钟电影的数量,出现的频率)等信息,应该如何呈现这些数据?

# 数据
a = [131,  98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115,  99, 136, 126, 134,  95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117,  86,  95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123,  86, 101,  99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140,  83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144,  83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137,  92,121, 112, 146,  97, 137, 105,  98, 117, 112,  81,  97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112,  83,  94, 146, 133, 101,131, 116, 111,  84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]

把数据进行分组统计,组数要适当,组数太少会产生统计误差较大的问题。
组数:将数据分组,当数据在100个以内时,按数据多少常分为5~12组。
组距:指每个小组的两个端点的距离。
组数=极差/组距

from matplotlib import pyplot as plt
from matplotlib import font_manager

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

a = [131,  98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115,  99, 136, 126, 134,  95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117,  86,  95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123,  86, 101,  99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140,  83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144,  83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137,  92,121, 112, 146,  97, 137, 105,  98, 117, 112,  81,  97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112,  83,  94, 146, 133, 101,131, 116, 111,  84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]

# 计算组数
d = 5   # 组距
num_bins = (max(a) - min(a))//d

plt.figure(figsize=(20,8), dpi=80)
plt.hist(a, num_bins)

# 设置x轴的刻度
plt.xticks(range(min(a), max(a)+d, d))  # “+d”是为了把max值包含进去

plt.grid()

plt.show()

在这里插入图片描述
由图中可以发现直方图在偏移,即直方图的绘制组距并非手工设定的组距。原因在于本实例中虽然手工设置组距为5,但是绘制图形时“plt.hist(a, num_bins)”即“a/组数”并没有取整,也就是得到的组距并不等于5,存在偏差。
关于matplotlib绘制直方图偏移的问题

# 只需修改
plt.hist(a, range(min(a), max(a)+d, d))

matplotlib.pyplot.hist文档
如果需要查看频率分布直方图,则增加参数density

# 修改为
plt.hist(a, range(min(a), max(a)+d, d), density=True)

在这里插入图片描述
①在美国2004年人口普查发现有124 million的人在离家相对较远的地方工作。根据他们从家到上班地点所需要的时间,通过抽样统计(最后一列)出了下表的数据,这些数据能否绘制成直方图。
在这里插入图片描述

interval = [0,5,10,15,20,25,30,35,40,45,60,90]
width = [5,5,5,5,5,5,5,5,5,15,30,60]
quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,47]

能够使用plt.hist方法的都是没有统计过的数据,统计后的数据无法使用hist方法。统计后的数据为了达到直方图的效果,需要绘制条形图。下面使用条形图的方法 将统计后的数据绘制成直方图的样子。

from matplotlib import pyplot as plt
from matplotlib import font_manager

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

interval = [0,5,10,15,20,25,30,35,40,45,60,90]
wid = [5,5,5,5,5,5,5,5,5,15,30,60]
quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,47]

plt.figure(figsize=(20,8), dpi=80)

plt.bar(range(len(quantity)), quantity, width=1, align='edge')
# width默认0.8,width=1 时各条之间没有间隔,align控制条形与x坐标的齐,默认center,edge为左对齐
x_labels = interval + [150] # 为了让图形完整,增加最后坐标即90+60=150,
plt.xticks(range(len(quantity)+1), x_labels)    # x轴做标数+1

plt.grid()

plt.show()

在这里插入图片描述
然而采用上面的方法绘制条形图并没有使用所给的width数据,通过修改原数据达到效果

from matplotlib import pyplot as plt
from matplotlib import font_manager
import numpy as np

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

interval = [0,5,10,15,20,25,30,35,40,45,60,90]
wid = [5,5,5,5,5,5,5,5,5,15,30,60]
quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,47]

counts = np.bincount(wid)
# np.bincount方法返回了一个长度为nums最大值的列表,列表中的每个值代表其索引位数值出现在nums中的次数
# 返回众数
d = np.argmax(counts)   # 组距

# 调整数据来利用width,得到新数据new_quantity
new_quantity = []
k = 0
for i in range(len(wid)):
    time = 0    # 初始化重复两坐标点相距非设定组距的数据的次数
    j = 0       # 计数
    if wid[i] != d:
        time = wid[i]/d - 1      # 计算time
    new_quantity += [quantity[k]]
    k = k+1
    while(j!=time):
        new_quantity += [quantity[k-1]] # 重复数据
        j = j+1
# print(new_quantity)        

new_interval = np.arange(0, d*(len(new_quantity)+1), d)
# print(new_interval)       
plt.figure(figsize=(20,8), dpi=80)

plt.bar(range(len(new_quantity)), new_quantity, width=1, align='edge')
# width默认0.8,width=1 时各条之间没有间隔,align控制条形与x坐标的齐,默认center,edge为左对齐
plt.xticks(range(len(new_quantity)+1), new_interval)    # x轴做标数+1

plt.show()

在这里插入图片描述
直方图的应用场景:
①用户的年龄分布状态
②一段时间内用户点击次数的分布状态
③用户活跃时间的分布状态

(8)阶段总结
①明确应该选择哪种图形来呈现数据
②折线图 plt.plot(x,y)
③条形图 plt.bar(x,y)
④散点图 plt.scatter(x,y)
⑤直方图 plt.hist(data, bins, density)
⑥xticks和yticks
⑦label、title和grid
⑧plt.figure和plt.savefig
⑨matplotlib使用流程:明确问题–》选择图形的呈现方式–》准备数据–》绘图和图形完善
⑩除了matplotlib外还可以使用前端框架来画图,例如echarts (echarts gallery)、plotly(Plotly Python Graphing Library

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值