matplotlib常用图形

作者 张旭 日期 2017-03-15
matplotlib常用图形

解决中文字体不能显示问题

http://www.pythoner.com/200.html

  1. 进入Python安装目录下的Lib\site-packages\matplotlib\mpl-data目录,

    cd (你的python 目录)\site-packages\matplotlib\mpl-data
  2. 打开matplotlibrc文件

  3. 删除font.family和font.sans-serif两行前的#,

    font.family : sans-ser
    font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
  4. 并在font.sans-serif后添加微软雅黑字体(Microsoft YaHei)

    font.family : sans-ser
    font.sans-serif : Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

引入seaborn

为了画图更漂亮,引入seaborn。但中文又乱码了,真是个美丽的错误

import seaborn as sns
sns.set_style("darkgrid",{"font.sans-serif":['Microsoft YaHei', 'Arial']})
#字体填入你的机器支持的字体名称

https://github.com/mwaskom/seaborn/issues/1009

import os
os.path
<module 'posixpath' from '/home/xu/venv/lib/python3.5/posixpath.py'>

Simple Plot

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style("darkgrid",{"font.sans-serif":['Microsoft YaHei', 'Arial']})
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title(u'实例')
plt.grid(True)
plt.savefig("test.png")
plt.show()

png

Alt text

Subplot demo

import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(16,9))
x1=[0,1,2,3,4,5]
x2 = np.linspace(0.0, 2.0)
y1 = [-1,-10,3,9,-4,5]
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, '-o')
plt.xlabel('X doggy')
plt.ylabel('Damped oscillation')
plt.title('A tale of 2 subplots')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.:r')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.title('A tale of 2 subplots')
plt.show()

png

plt.plot?
import seaborn
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
np.random.seed(0)
# 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, normed=1)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

png

Histograms

np.random.randn(4)
array([ 0.00529265,  0.8005648 ,  0.07826018, -0.39522898])
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
np.random.seed(0)
# example data
mu = 0 # mean of distribution
sigma = 100 # standard deviation of distribution
x = mu + sigma * np.random.randn(437)
num_bins = 30
fig, ax = plt.subplots()
# the histogram of the data
n, bins, patches = ax.hist(x, num_bins)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax.plot(bins, y, '--')
ax.set_xlabel(u'Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu={}$, $\sigma={}$'.format(mu,sigma))
plt.grid(True)
# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

png

jointplot

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import kendalltau
import seaborn as sns
sns.set(style="ticks")
rs = np.random.RandomState(11)
x = rs.gamma(2, size=1000)
y = -.5 * x + rs.normal(size=1000)
plt.subplot(2, 1, 1)
sns.jointplot(x, y, kind="kde", stat_func=kendalltau, color="#9CB391",space=0.5)
plt.subplot(2, 1, 2)
sns.jointplot(x, y, kind="hex", stat_func=None, color="#9CB391")
plt.show()

png

png

png

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="ticks")
# Load the example dataset for Anscombe's quartet
df = sns.load_dataset("anscombe")
# Show the results of a linear regression within each dataset
sns.lmplot(x="x", y="y", col="dataset", hue="dataset", data=df,
col_wrap=2, ci=None, palette="muted", size=4,
scatter_kws={"s": 50, "alpha": 1})
plt.show()

png

heatmap

import numpy as np
from scipy.stats import kendalltau
import seaborn as sns
sns.set(style="ticks")
rs = np.random.RandomState(11)
x = rs.gamma(2, size=1000)
y = -.5 * x + rs.normal(size=1000)
sns.jointplot(x, y, kind="hex", stat_func=kendalltau, color="#4CB391")
plt.show()

png

from pandas import DataFrame
df = DataFrame({'X':['d','g','d','miao',9,3],'Y':[11,12,13,14,15,16],'Z':[10,20,30,40,50,60]})
import matplotlib.pyplot as plt
plt.plot([1,9,3,4],'-o')
plt.ylabel('some numbers')
plt.axis([0, 6, 0, 20])
plt.show()

png

Matplotlib 修饰

X轴,Y轴标签

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers',fontsize=18)
plt.show()

png

X,Y 轴范围

import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([-6, 6, -5, 20])
plt.show()

png

点型,线型

import numpy as np
import matplotlib.pyplot as plt
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
p1,p2,p3=plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

png

折线图

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,4.7,5.8], [8,4,9,0,2.5,17.4], 'r-o',linewidth=2)
plt.axis([0, 6, 0, 20])
plt.show()

png

Controlling line properties 控制线型

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
[None, None, None, None]
lines = plt.plot([1, 2, 3])
plt.setp(lines)
agg_filter: unknown
alpha: float (0.0 transparent through 1.0 opaque) 
animated: [True | False] 
antialiased or aa: [True | False] 
axes: an :class:`~matplotlib.axes.Axes` instance 
clip_box: a :class:`matplotlib.transforms.Bbox` instance 
clip_on: [True | False] 
clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] 
color or c: any matplotlib color 
contains: a callable function 
dash_capstyle: ['butt' | 'round' | 'projecting'] 
dash_joinstyle: ['miter' | 'round' | 'bevel'] 
dashes: sequence of on/off ink in points 
drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] 
figure: a :class:`matplotlib.figure.Figure` instance 
fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] 
gid: an id string 
label: string or anything printable with '%s' conversion. 
linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
linewidth or lw: float value in points 
marker: :mod:`A valid marker style <matplotlib.markers>`
markeredgecolor or mec: any matplotlib color 
markeredgewidth or mew: float value in points 
markerfacecolor or mfc: any matplotlib color 
markerfacecoloralt or mfcalt: any matplotlib color 
markersize or ms: float 
markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effects: unknown
picker: float distance in points or callable pick function ``fn(artist, event)`` 
pickradius: float distance in points 
rasterized: [True | False | None] 
sketch_params: unknown
snap: unknown
solid_capstyle: ['butt' | 'round' |  'projecting'] 
solid_joinstyle: ['miter' | 'round' | 'bevel'] 
transform: a :class:`matplotlib.transforms.Transform` instance 
url: a url string 
visible: [True | False] 
xdata: 1D array 
ydata: 1D array 
zorder: any number 

多图和多轴

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

png

import matplotlib.pyplot as plt
# the first figure
plt.subplots(figsize=(20, 10))
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])
plt.figure(2) # a second figure
plt.plot([4, 5, 6],'-o') # creates a subplot(111) by default
plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title
plt.show()

png

png

使用文本 Working with text

xlabel,ylabel,title,text 都可以使用文本

import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')#\sum _{ i=0 }^{ 1000 }{ x3 }
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

png

使用数学表达式 Using mathematical expressions in text

使用TeX 表达式 equation expressions
Tex表达式生成网址

注释文本 Annotating text

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()

png

对数轴 和其他非线性轴 Logarithmic and other nonlinear axis

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(figsize=(20,10))
# 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()

png

图片的放大与缩小

plt.figure(figsize=(16,9))fig, ax = plt.subplots(figsize=(20, 10))

import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(16,9))
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()

png