matplotlib 的密度图与等高线图
代码
import numpy as np
import pandas as pd
import numexpr
import time
from datetime import datetime
import matplotlib as mpl
import matplotlib.pyplot as plt
from dateutil import parser
plt.style.use('seaborn-whitegrid')
# 有时在二维图上用等高线图或者彩色图来表示三维数据是个不错的方法。
# Matplotlib 提供了三个函数来解决这个问题:
# 用plt.contour画等高线图、用plt.contourf画带有填充色的等高线图(filled contour plot)的色彩、
# 用 plt.imshow显示图形。
# 密度图与等高线图
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy', alpha=0.5)
plt.colorbar();
plt.show()
# 频次直方图、数据区间划分和分布密度
data = np.random.randn(1000)
plt.hist(data, bins=30, alpha=0.5,
histtype='stepfilled', color='steelblue',
edgecolor='none')
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs)
plt.show()
# 二维频次直方图与数据区间划分
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30, cmap='Blues')
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
plt.show()