数据可视化,matplotlib散点图

2、制作散点图

很尴尬啊,我已经忘记了我自己还有这么一个专栏,中间断了足足一年,赶紧回来给续上。

matplotlib的散点图应该是最基础的应用了,这里就先给出一个简单的例子,如果有人急着用来不及学习就可以拿走直接复制粘贴再改一改。

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(0,10,11)

y = np.sin(x)

plt.scatter(x, y)

plt.show()

最后一行的这个plt.show()在jupyter notebook中是不必加上的,不会影响出图。但是如果你使用的的是一个集成的编辑器比如pycharm什么的,那就需要加上这句话,否则程序运行后你是看不见生成的图的。

我这里的演示就直接用cmd了,没必要再建立一个新文件。

最简单的散点图

不知道大家注意到没有,我这里没有使用之前建立画布的语句,因为我这里只是为了快速出图,采用的面向过程的模式,而建立画布再进行操作应该是属于面向对象的思路了,我再画一次。

建立对象版

这种模式相较于前一种可以更好地控制结果图,包括大小和颜色等参数,建议在一开始就习惯这种OOP写法。

最后放上两个来自gallery的绘图,比较漂亮。

import matplotlib.pyplot as plt

import numpy as np

# unit area ellipse

rx, ry = 3., 1.

area = rx * ry * np.pi

theta = np.arange(0, 2 * np.pi + 0.01, 0.1)

verts = np.column_stack([rx / area * np.cos(theta), ry / area * np.sin(theta)])

x, y, s, c = np.random.rand(4, 30)

s *= 10**2.

fig, ax = plt.subplots()

ax.scatter(x, y, s, c, marker=verts)

plt.show()

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.cbook as cbook

# Load a numpy record array from yahoo csv data with fields date, open, close,

# volume, adj_close from the mpl-data/example directory. The record array

# stores the date as an np.datetime64 with a day unit ('D') in the date column.

with cbook.get_sample_data('goog.npz') as datafile:

    price_data = np.load(datafile)['price_data'].view(np.recarray)

price_data = price_data[-250:]  # get the most recent 250 trading days

delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1]

# Marker size in units of points^2

volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2

close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]

fig, ax = plt.subplots()

ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)

ax.set_xlabel(r'$\Delta_i$', fontsize=15)

ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=15)

ax.set_title('Volume and percent change')

ax.grid(True)

fig.tight_layout()

plt.show()


这几个程序都用到了numpy 函数库,如果有没有用过的同学建议自己先学一下。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容