Python基础绘图教程(一)

时间:2022-07-26
本文章向大家介绍Python基础绘图教程(一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

作为一名科研人员,如何更好的绘制图像一直是小编关注的问题,尤其在写论文的时候,一张美观、制作精良、逼格高大上的配图无形间就给你的论文加上了梦想冲击顶刊的翅膀。本期小编就教你如何使用Python绘制图像。

Python是一种耳熟能详的程序设计语言,具有较强的可视化能力,较常使用的可视化库主要有matplotlib(https://matplotlib.org/)、seaborn(http://seaborn.pydata.org/)、geoplotlib(https://residentmario.github.io/geoplot/index.html)等等,这些库均配有官方的教程、样例供大家学习,有兴趣的读者可以点开上述链接自行去解锁新技能。这里小编主要就介绍地学领域常用的几种图像类型。

1 线型图

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

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()
plt.show()

2 柱状图/概率分布图

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

np.random.seed(19680801)

# example data
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(437)

num_bins = 50

fig, ax = plt.subplots()

# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, density=1)

# add a 'best fit' line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram: $mu=100$, $sigma=15$')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

3 填色图/热点图

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# sphinx_gallery_thumbnail_number = 2

leadtime = ["lead 1 mon", "lead 2 mon", "lead 3 mon", "lead 4 mon",
              "lead 5 mon", "lead 6 mon"]
param = ["Temperature", "Wind", "Precipitation",
           "SLP", "Humidity", "Heat flux"]

coef = np.array([[0.95, 0.9, 0.85, 0.8, 0.82, 0.7],
                    [0.93, 0.86, 0.82, 0.78, 0.8, 0.65],
                    [0.88, 0.82, 0.8, 0.72, 0.75, 0.62],
                    [0.85, 0.78, 0.75, 0.68, 0.7, 0.56],
                    [0.8, 0.72, 0.7, 0.65, 0.68, 0.5],
                    [0.78, 0.68, 0.65, 0.6, 0.6, 0.45],])

fig, ax = plt.subplots()

im, cbar = heatmap(coef, leadtime, param, ax=ax,
                   cmap="PiYG", cbarlabel="Correlation Coefficient")
texts = annotate_heatmap(im, valfmt="{x:.2f}")

fig.tight_layout()
plt.show()

4 点图&等值线图

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

np.random.seed(19680801)
npts = 200
ngridx = 100
ngridy = 200
x = np.random.uniform(-2, 2, npts)
y = np.random.uniform(-2, 2, npts)
z = x * np.exp(-x**2 - y**2)

fig, ax1 = plt.subplots()
# -----------------------
# Interpolation on a grid
# -----------------------
# A contour plot of irregularly spaced data coordinates
# via interpolation on a grid.
# Create grid values first.
xi = np.linspace(-2.1, 2.1, ngridx)
yi = np.linspace(-2.1, 2.1, ngridy)

# Linearly interpolate the data (x, y) 
# on a grid defined by (xi, yi).
triang = tri.Triangulation(x, y)
interpolator = tri.LinearTriInterpolator(triang, z)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)

# Note that scipy.interpolate provides means to 
#interpolate data on a grid as well. The following 
# would be an alternative to the four lines above:
#from scipy.interpolate import griddata
ax1.contour(xi, yi, zi, levels=14, linewidths=0.5, colors='k')
cntr1 = ax1.contourf(xi, yi, zi, levels=14, cmap="RdBu_r")
fig.colorbar(cntr1, ax=ax1)
ax1.plot(x, y, 'ko', ms=3)
ax1.set(xlim=(-2, 2), ylim=(-2, 2))
ax1.set_title('grid and contour (%d points, %d grid points)'%
              (npts, ngridx * ngridy))
plt.show()

本期的介绍就到这里了,文中代码可以横向滑动浏览,为方便实操,相关的代码和样例存已存放至百度网盘,链接: https://pan.baidu.com/s/1uSGDqbeCAh1ZS-dz-zs5tA 提取码: 8n9x,读者朋友们可以前往下载学习。

参考链接

https://matplotlib.org/gallery/index.html

最后小编想说,Python,NCL,Matlab等都是比较常用的数据处理和绘图软件,各有各的优势和特点,当然工具不在于多而在于精,找到适合自己的工具并熟练掌握才是最重要的。