使用matplotlib绘制图表
安装
pip install matplotlib
这篇官方教程通俗易懂,看完能有基本的了解和使用。
中文显示问题
下载simhei.ttf(或其它中文ttf字体),并放到相应Python版本的site-packages/matplotlib/mpl-data/fonts/ttf
目录。
代码中添加
# 设置中文
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus']=False
如果不起作用,删除缓存rm -rf ~/.matplotlib/fontList.py3k.cache
示例
示例一:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19690801)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(1000)
plt.hist(x, 50, normed=True, facecolor='g', alpha=0.75)
plt.text(60, 0.025, r'$\mu=100,\ \sigma=15$')
plt.annotate('here', xy=(105, 0.03), xytext=(110, 0.035), color='r',
arrowprops=dict(facecolor='r', shrink=0.05))
plt.axis([40, 160, 0.0, 0.04])
plt.grid(True)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.show()
示例二:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter # useful for `logit` scale
# Fixing random state for reproducibility
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure(1)
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()