第4天|16天搞定Python数据分析,图表,靓靓靓

liftword5个月前 (12-20)技术文章48

统计图是根据统计数字,用几何图形、事物形象和地图等绘制的各种图形。它具有直观、形象、生动、具体等特点。统计图可以使复杂的统计数字简单化、通俗化、形象化,使人一目了然,便于理解和比较。

在上一篇《第3天|16天搞定Python数据分析,Matplotlib 》中,我们在学习Matplotlib的基本用法时,开发实现了线状图和散点图,它们就是统计图来的。这一节我们将用Matplotlib实现更多的统计图,希望在你的开发中,能用得上。

4.1 堆叠图

堆叠图可可以用来比较在一个区间内的多个变量。是一种特殊的面积图,每个数据系列的起点都是基于前一个数据系列绘制的,也就是每度量一行就要填满行与行之间的区域。温馨提醒:新增了去掉了上边和右边的坐标轴的知识点。

import matplotlib.pyplot as plt

""" Windows系统用
# plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False"""
# macOS系统用
plt.rcParams["font.sans-serif"] = "Songti SC"
plt.rcParams["axes.unicode_minus"] = False
labels = ["手机", "平板", "电脑", "电视", "冰箱"]
cost = [51.25, 45.12, 62.25, 35.20, 45.52]
gain = [22.00, 16.21, 30.36, 19.13, 31.25]
width = 0.35
fig, ax = plt.subplots(figsize=(9, 6))
# 去掉顶部和右边坐标轴
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# 成本
ax.bar(labels, cost, width, label="成本")
# 利润
ax.bar(labels, gain, width, label="利润")
ax.set_ylabel("销售额(万元)")
ax.set_title("双29电器销售成本和利润分析")
ax.legend()
fig.savefig("test.png")

输出结果

4.2 柱状图

柱状图又称条形图、质量分布图,能够使人们一眼看出各个数据的大小,易于比较数据之间的差别和清楚地表示出数量的多少,是一种通过柱形的高度来表现数据大小的一种常用图表类型。

import matplotlib.pyplot as plt
import numpy as np

""" Windows系统用
# plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False"""
# macOS系统用
plt.rcParams["font.sans-serif"] = "Songti SC"
plt.rcParams["axes.unicode_minus"] = False
labels = ["1月", "2月", "3月", "4月", "5月", "6月"]
screw = [2, 6, 9.2, 1.5, 2.2, 3.2]
nail = [2.8, 5.5, 6.2, 3.6, 1.5, 1.2]
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots(figsize=(9, 6))
# 去掉顶部和右边坐标轴
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
rects1 = ax.bar(x - width / 2, screw, width, label="螺丝")
rects2 = ax.bar(x + width / 2, nail, width, label="钉子")
ax.set_ylabel("销售额(万元)")
ax.set_title("2020年螺丝钉子销售分析")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# 保存图片
fig.savefig("test.png")

输出结果

4.3 饼图

饼图主要用于展现不同类别数值相对于总数的占比情况。图中每个分块(扇区)的弧长表示该类别的占比大小,所有分块数据总和为100%。温馨提醒:新增设置标题在底部知识点

import matplotlib.pyplot as plt

""" Windows系统用
# plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False"""
# macOS系统用
plt.rcParams["font.sans-serif"] = "Songti SC"
plt.rcParams["axes.unicode_minus"] = False
# 指定画布大小,默认为600*480
fig, ax = plt.subplots(figsize=(9, 6))
labels = ["热狗", "鸡蛋饼", "冰淇淋", "老冰棍"]
sizes = [15, 30, 45, 10]
ax.pie(sizes, labels=labels, autopct='%1.1f%%',
       shadow=True, startangle=90)
ax.set_title("吃货的最爱占比分析", y=-0.1)
fig.savefig("test.png")

输出结果

4.4 折线图

折线图用来表示事物的发展变化趋势,主要用于计量资料,描述两个变量间关系,是用折线将各个数据点标志连接起来的图表,用于展现数据的变化趋势。温馨提醒:新增去掉网格线的知识点

import matplotlib.pyplot as plt
import numpy as np

""" Windows系统用
# plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False"""
# macOS系统用
plt.rcParams["font.sans-serif"] = "Songti SC"
plt.rcParams["axes.unicode_minus"] = False
# 指定画布大小,默认为600*480
fig, ax = plt.subplots(figsize=(9, 6))
t = np.arange(0.0, 3.0, 0.01)
# 正弦
s = 1 + np.sin(3 * np.pi * t)
c = 1 + np.cos(2 * np.pi * t)
ax.plot(t, s)
ax.plot(t, c)
ax.set(xlabel='时间(s)', ylabel='电压(V)',
       title='电压随着时间的变化趋势图')
ax.grid(False)
fig.savefig("test.png")

输出结果

4.5 散点图

散点图在直角坐标系显示数据的两个变量(X和Y轴)之间的关系,数据显示为点的集合,适合用于在不考虑时间的情况下比较大量的数据点。温馨提醒:新增换了一种主题风格知识点。

import matplotlib.pyplot as plt
import numpy as np

# 指定画布大小,默认为600*480
fig, ax = plt.subplots(figsize=(9, 6))
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# 指定主题
plt.style.use("seaborn-deep")
x = np.random.randn(60)
y = np.random.randn(60)
sizes = np.random.rand(60) * 600
plt.scatter(x, y, c=[i for i in range(60)], s=sizes, alpha=0.6)
# 保存图片
fig.savefig("test.png")

输出结果

4.6 雷达图

雷达图又称蜘蛛网图,适用于显示三个或更多的维度的变量。雷达图是以在同一点开始的轴上显示的三个或更多个变量的二维图表的形式来显示多元数据的方法。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(9, 6))
np.random.seed(21521910)
N = 30
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
colors = plt.cm.viridis(radii / 10.0)
ax = plt.subplot(111, projection='polar')
ax.bar(theta, radii, width=width, bottom=0.0, color=colors, alpha=0.5)
fig.savefig("test.png")

输出结果

4.7 条形码

条形码)是将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符。在生活、工作当中经常见到,matplotlib怎能错过呢?温馨提醒:新增去掉X、Y轴刻度的知识点。尽管matplotlib可以实现条形码的效果,但Python有专用的条形码和二维码库。我放在这里,只是是为了演示去掉X、Y轴刻度。

import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(600)
barprops = dict(aspect='auto', cmap='binary', interpolation='nearest')
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.1, 0.8])
ax1.set_axis_off()
ax1.imshow(x.reshape((-1, 1)), **barprops)
ax2 = fig.add_axes([0.3, 0.4, 0.6, 0.2])
ax2.set_axis_off()
ax2.imshow(x.reshape((1, -1)), **barprops)
fig.savefig("test.png")

输出结果

4.8 动态图

静态图看多了,是不是感觉挺无聊的,好在matplotlib是可以支持动态图。在统计图的基础上,加上动态效果,说不定老板一高兴,就给你介绍个女朋友啦。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots(figsize=(9, 6))
x = np.arange(0, 2 * np.pi, 0.01)
line, = ax.plot(x, np.sin(x))


def animate(i):
    line.set_ydata(np.sin(x + i / 50))
    return line,


ani = animation.FuncAnimation(
    fig, animate, interval=20, blit=True, save_count=50)
ani.save("line.gif")

动态图,自己运行看看是什么效果吧,学编程,要多动手练一练,不能只顾看了。

好了,有关matplotlib实现常见统计图的内容,老陈讲完了,如果你想要学习更多的知识,可去matplotlib官网https://matplotlib.org进行深造。如果你觉得本文对你有所帮助的话,希望老铁能转发点赞,让更多的人看到这篇文章。你的转发和点赞,就是对老陈继续创作和分享最大的鼓励。

一个当了10年技术总监的老家伙,分享多年的编程经验。想学编程的朋友,可关注今日头条:老陈说编程。分享Python,前端(小程序)、App和嵌入式方面的干货。关注我,没错的。

#Python##数据分析##统计图##程序员##大数据#

相关文章

"Python数据分析基石:Pandas全方位解析(史上最全面!)"

pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快...

python数据分析入门教程(小白福利)

身处大数据时代,数据分析已经逐渐成为必备技能,python作为当今最火的数据分析工具之一,拥有丰富和强大的库,而且和其他编程语言相比较简单,只要认真学,小白也能入门。今天给大家分享一个python数据...