玩玩Matplotlib

上一篇聊到了Kaggle中房价评估的项目,在处理数据集中的数据之前,先看下如何把一批批的数据图形化展示出来。这就会用到Matplotlib库了。

Matplotlib是什么?

Matplotlib:可以将数据进行可视化展示的强大库。

Matplotlib怎么用?

把数据画出来

  • 准备一一对应的一组数据,即 y = f(x),交给plt画出来

Numpy我们下次再说

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif']=['SimHei']
x = np.linspace(0, 2, 100)
y = x**2
plt.plot(x, y)
plt.title('Numpy我们下次再说')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.show()
image
  • 还可以将多组数据画在一起
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.title('三组数据放一起')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()
image

设置画板

  • 给画板设置坐标轴的个数
fig = plt.figure()
fig.suptitle('firure → 画板')
fig, ax_lst = plt.subplots(3, 2) # 3行2列个坐标轴
image
  • 指定坐标轴画指定的数据
x = np.linspace(0, 2, 100)
y1 = x
y2 = x**2
y3 = x**3
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, y1)
ax1.plot(x, y2)
ax2.plot(x, y1)
ax2.plot(x, y3)
ax1.axis([0, 4, 0, 4])
image
  • 指定画数据的类型
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

ax1 = plt.subplot(2, 3, 1)
x = ['二零一七年', '二零一八年', '二零一九年']
y = [2017, 2018, 2019]
ax1.axis([-1, 3, 2000, 2025])
ax1.bar(x, y)

ax2 = plt.subplot(2, 3, 2, sharey=ax1)
x = [1, 2, 3]
y = [1, 10, 7]
ax2.scatter(x, y)

ax3 = plt.subplot(2, 3, 3, sharey=ax1)
ax3.plot(x, y)

import random
x = random.sample(range(1000), 30)
# x.extend(random.sample(range(100), 20))
# x = np.linspace(0, 2, 100)
ax4 = plt.subplot(2, 3, 4)
ax4.hist(x, 70)

ax5 = plt.subplot(2, 3, 6, sharey=ax4)
x = ['二零一七年', '二零一八年', '二零一九年']
y = [0.8, 0.5, 0.6]
explode = (0.1, 0.1, 0)
ax5.pie(y, explode=explode, labels=x, autopct='%1.1f%%',
        shadow=True, startangle=90)
image

下一篇,我会聊下不同维度的数据如何展示。

参考资料

[1] https://matplotlib.org/tutorials/index.html#introductory

你可能感兴趣的:(玩玩Matplotlib)