Last active
January 22, 2020 09:34
-
-
Save whiledoing/cb78d81b721e7f80905773d7c335a1e5 to your computer and use it in GitHub Desktop.
[matplotlib-snippets] matplotlib snippets #matplotlib #python #visualization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def f(x, y): | |
return np.sin(x) ** 10 + np.cos(10+x*y) + np.cos(x) | |
x = np.linspace(0, 5, 50) | |
y = np.linspace(0, 5, 50) | |
X, Y = np.meshgrid(x, y) | |
Z = f(X, Y) | |
# draw contour | |
contour = plt.contour(X, Y, Z, 3, colors='black') | |
# add z value into contour | |
plt.clabel(contour, fontsize=10, inline=True) | |
# plus transparent bg from imshow | |
# RdGy => RedGray | |
plt.imshow(Z, extent=[0, 5.0, 0, 5.0], origin='lower', cmap=plt.cm.RdGy, alpha=0.3) | |
# show color bar | |
plt.colorbar() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# load images of the digits 0 through 5 and visualize several of them | |
from sklearn.datasets import load_digits | |
digits = load_digits(n_class=6) | |
# use ax.flat to draw all images in one-loop | |
fig, ax = plt.subplots(8, 8, figsize=(6, 6)); | |
for i, axi in enumerate(ax.flat): | |
axi.imshow(digits.images[i]); | |
axi.set(xticks=[], yticks=[]); | |
# project the digits into 2 dimensions using IsoMap | |
from sklearn.manifold import Isomap | |
iso = Isomap(n_components=2) | |
projection = iso.fit_transform(digits.data) | |
# plot the results | |
# vip: use discreate cmap to distinguish different digit label's color | |
plt.scatter(projection[:, 0], projection[:, 1], lw=0.1, | |
c=digits.target, cmap=plt.cm.get_cmap('cubehelix', 6)) | |
# set ticks in colorbar | |
plt.colorbar(ticks=range(6), label='digit value') | |
# make ticks 1,2,3,4,5 center in the box | |
plt.clim(-0.5, 5.5) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create some normally distributed data | |
mean = [0, 0] | |
cov = [[1, 1], [1, 2]] | |
x, y = np.random.multivariate_normal(mean, cov, 3000).T | |
# Set up the axes with gridspec | |
fig = plt.figure(figsize=(6, 6)) | |
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2) | |
# use top-right 3*3 grid | |
main_ax = fig.add_subplot(grid[:-1, 1:]) | |
# share y axis | |
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax) | |
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax) | |
# scatter points on the main axes | |
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2) | |
# histogram on the attached axes | |
x_hist.hist(x, 40, histtype='stepfilled', | |
orientation='vertical', color='gray') | |
x_hist.invert_yaxis() | |
# invert axis | |
y_hist.hist(y, 40, histtype='stepfilled', | |
orientation='horizontal', color='gray') | |
y_hist.invert_xaxis() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 用matplotlib画hello的点集 | |
# 1. 基于text生成一个png图像 | |
# 2. 读取图像,随机取点阵,在png图像中有像素的点,就是一个目标点 | |
# 3. 图像用scatter画出 | |
# [from](https://jakevdp.github.io/PythonDataScienceHandbook/05.10-manifold-learning.html) | |
def make_hello(N=1000, rseed=42): | |
# Make a plot with "HELLO" text; save as PNG | |
fig, ax = plt.subplots(figsize=(4, 1)) | |
fig.subplots_adjust(left=0, right=1, bottom=0, top=1) | |
ax.axis('off') | |
ax.text(0.5, 0.4, 'hello', va='center', ha='center', weight='bold', size=85) | |
fig.savefig('img/hello.png') | |
plt.close(fig) | |
# Open this PNG and draw random points from it | |
from matplotlib.image import imread | |
# imread得到的结果,按照左上角为原点,(y,x)的方式组织 | |
# 所以读取后,第一个维度装置,变为左下角为原点;第二个维度保持;取第三个维度的r通道 | |
# 判断是否存在数据即可;最终再装置一下,得到(x,y) 的排列 | |
src = imread('img/hello.png') | |
data = src[::-1, :, 0].T | |
rng = np.random.RandomState(rseed) | |
X = rng.rand(4 * N, 2) | |
# 乘以data.shape就是将[0, 1.0]的数据扩展到data的维度 | |
i, j = (X * data.shape).astype(int).T | |
mask = (data[i, j] < 1) | |
X = X[mask] | |
# 找到之后,记得X的数据,x,y的范围都是[0, 1.0],所以将y的长度记作1.0,x的长度需要扩展一下 | |
X[:, 0] = X[:, 0] * (data.shape[0] / data.shape[1]) | |
# 取得前N个数,再基于argsoft得到排序后的索引给,进而得到最终排序后的前N个有图像内容的数据点 | |
X = X[:N] | |
return X[np.argsort(X[:, 0])] | |
X = make_hello() | |
# 将X离散到[0.0, 4.0]的好处就是可以指定color | |
# 如果指定离散的color数量,需用get_cmap | |
plt.scatter( | |
X[:, 0], X[:, 1], | |
c=X[:, 0], | |
cmap='rainbow', #plt.cm.get_cmap('rainbow', 5)); | |
alpha=.5, | |
edgecolors=None | |
) | |
# 保证X和Y轴的数据1:1的单位长度,调整图片的大小来适配 | |
plt.axis('scaled'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hist_and_lines(): | |
np.random.seed(0) | |
fig, ax = plt.subplots(1, 2, figsize=(11, 4)) | |
ax[0].hist(np.random.randn(1000)) | |
for i in range(3): | |
ax[1].plot(np.random.rand(10)) | |
ax[1].legend(['a', 'b', 'c'], loc='lower left') | |
with plt.style.context('bmh'): | |
hist_and_lines() | |
with plt.style.context(['seaborn']): | |
hist_and_lines() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from https://jakevdp.github.io/PythonDataScienceHandbook/04.10-customizing-ticks.html | |
fig, ax = plt.subplots() | |
x = np.linspace(0, 3 * np.pi, 1000) | |
ax.plot(x, np.sin(x), lw=3, label='Sine'); | |
ax.plot(x, np.cos(x), lw=3, label='Cosine'); | |
# Set up grid, legend, and limits | |
ax.grid(True) | |
ax.legend(frameon=False) | |
# xlim = ylim | |
ax.axis('equal') | |
ax.set_xlim(0, 3 * np.pi); | |
# set locator to be product of pi/2 | |
ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi/2)); | |
ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi/4)); | |
# mapping xticks to Latex | |
def format_func(value, tick_number): | |
# find number of multiples of pi/2 | |
N = int(np.round(2 * value / np.pi)) | |
if N == 0: | |
return "0" | |
elif N == 1: | |
return r"$\pi/2$" | |
elif N == 2: | |
return r"$\pi$" | |
elif N % 2 > 0: | |
return r"${0}\pi/2$".format(N) | |
else: | |
return r"${0}\pi$".format(N // 2) | |
# use plt.FuncFormatter to format xticks | |
ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment