matplotlib之pyplot 学习示例
现在通过numpy和matplotlib.pyplot 在Python上实现科学计算和绘图,而且和matlab极为相像(效率差点,关键是方便简单)
这里有大量plots代码例子。
其他网址链接
.plot 显示中文字符 | pyplot常用库函数大全 |
subplot 子图 |
1. 最简单的绘图实例
这是一个非常基本的带文字标签的plot()
:
import matplotlib.pyplot as plt
import numpy as np
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('About as simple as it gets, folks')
plt.grid(True)
plt.savefig("test.png")
plt.show()
2、subplot 示例
使用 subplot()
命令创建多个轴(即子图) :
import numpy as np
import matplotlib.pyplot as pltx1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')plt.show()
3、直方图(Histograms)
hist()
命令自动生成直方图并返回容器的计数或概率:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as pltnp.random.seed(0)
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()
4、路径示例
可以使用 matplotlib.path
模块在matplotlib中添加任意路径 :
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as pltfig, ax = plt.subplots()
Path = mpath.Path
path_data = [
(Path.MOVETO, (1.58, -2.57)),
(Path.CURVE4, (0.35, -1.1)),
(Path.CURVE4, (-1.75, 2.0)),
(Path.CURVE4, (0.375, 2.0)),
(Path.LINETO, (0.85, 1.15)),
(Path.CURVE4, (2.2, 3.2)),
(Path.CURVE4, (3, 0.05)),
(Path.CURVE4, (2.0, -0.5)),
(Path.CLOSEPOLY, (1.58, -2.57)),
]
codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')ax.grid()
ax.axis('equal')
plt.show()
5、3d图(mplot3d)
mplot3d工具包(请参阅mplot3d教程和 mplot3d示例)支持简单的3d图形,包括曲面,线框,散点图和条形图。
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as npfig = plt.figure()
ax = fig.gca(projection='3d')# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)plt.show()
6、流线图(Streamplot)
streamplot()
函数绘制矢量场的流线。除了简单绘制流线之外,它还允许将流线的颜色和/或线宽映射到单独的参数中,例如矢量场的速度或局部强度。
import numpy as np
import matplotlib.pyplot as pltY, X = np.mgrid[-3:3:100j, -3:3:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)fig0, ax0 = plt.subplots()
strm = ax0.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
fig0.colorbar(strm.lines)fig1, (ax1, ax2) = plt.subplots(ncols=2)
ax1.streamplot(X, Y, U, V, density=[0.5, 1])lw = 5*speed / speed.max()
ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)plt.show()
7、椭圆(Ellipses)
为了支持 凤凰号火星飞行任务(使用matplotlib显示航天器的地面跟踪),Michael Droettboom在Charlie Moad的基础上建立了一个非常精确的8次样条逼近椭圆弧(请参考资料 Arc
),并对缩放不敏感。
import matplotlib.pyplot as plt
import numpy.random as rnd
from matplotlib.patches import EllipseNUM = 250
ells = [Ellipse(xy=rnd.rand(2)*10, width=rnd.rand(), height=rnd.rand(), angle=rnd.rand()*360)
for i in range(NUM)]fig = plt.figure(0)
ax = fig.add_subplot(111, aspect='equal')
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(rnd.rand())
e.set_facecolor(rnd.rand(3))ax.set_xlim(0, 10)
ax.set_ylim(0, 10)plt.show()
8、条形图(Bar)
使用 bar() 命令创建条形图是简单的,它包括诸如自定义错误条等。
import numpy as np
import matplotlib.pyplot as pltn_groups = 5
means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35opacity = 0.4
error_config = {'ecolor': '0.3'}rects1 = plt.bar(index, means_men, bar_width,
alpha=opacity,
color='b',
yerr=std_men,
error_kw=error_config,
label='Men')rects2 = plt.bar(index + bar_width, means_women, bar_width,
alpha=opacity,
color='r',
yerr=std_women,
error_kw=error_config,
label='Women')plt.xlabel('Group')
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D', 'E'))
plt.legend()plt.tight_layout()
plt.show()
创建堆积条(bar_stacked.py)或水平条形图(barh_demo.py)也很简单。
9、饼图(Pie)
该 pie()
命令允许您轻松创建饼图。可选功能包括自动标记面积百分比,从饼图中心突起一个或多个楔子,以及阴影效果。仔细查看附件中的代码,只需几行代码即可生成此图。
import matplotlib.pyplot as plt
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.plt.show()
10、表的示例(Table)
table()
命令将一个文本表添加到轴。
import numpy as np
import matplotlib.pyplot as pltdata = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[ 139361, 331509, 343164, 781380, 52269]]columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]values = np.arange(0, 2500, 500)
value_increment = 1000# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)index = np.arange(len(columns)) + 0.3
bar_width = 0.4# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.array([0.0] * len(columns))# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x/1000.0) for x in y_offset])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='bottom')# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)plt.ylabel("Loss in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')plt.show()
11、散点图(Scatter)
该scatter()
命令使用(可选)大小和颜色参数生成散点图。此示例绘制了Google股票价格的变化情况,通过标记:反映交易量的尺寸和随时间变化的颜色。这里,alpha属性用于制作半透明的圆形标记。
import numpy as np
import matplotlib.pyplot as pltimport matplotlib.cbook as cbook
# Load a numpy record array from yahoo csv data with fields date,
# open, close, volume, adj_close from the mpl-data/example directory.
# The record array stores python datetime.date as an object array in
# the date column
datafile = cbook.get_sample_data('goog.npy')
try:
# Python3 cannot load python2 .npy files with datetime(object) arrays
# unless the encoding is set to bytes. However this option was
# not added until numpy 1.10 so this example will only work with
# python 2 or with numpy 1.10 and later
price_data = np.load(datafile, encoding='bytes').view(np.recarray)
except TypeError:
price_data = np.load(datafile).view(np.recarray)
price_data = price_data[-250:] # get the most recent 250 trading daysdelta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1]
# Marker size in units of points^2
volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2
close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]fig, ax = plt.subplots()
ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)ax.set_xlabel(r'$\Delta_i$', fontsize=15)
ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=15)
ax.set_title('Volume and percent change')ax.grid(True)
fig.tight_layout()plt.show()
12、滑块示例(Slider)
Matplotlib具有独立于所用图形用户界面的基本GUI控件,允许您编写跨GUI图形的控件。这个示例很有意思,大家多看看,详情请参阅matplotlib.widgets
和 widget examples。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtonsfig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0*np.sin(2*np.pi*f0*t)
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([0, 1, -10, 10])axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)def update(val):
amp = samp.val
freq = sfreq.val
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')def reset(event):
sfreq.reset()
samp.reset()
button.on_clicked(reset)rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)def colorfunc(label):
l.set_color(label)
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)plt.show()
13、填充演示(Fill)
fill()
命令让您绘制填充曲线和多边形:
import numpy as np
import matplotlib.pyplot as pltx = np.linspace(0, 1, 500)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)fig, ax = plt.subplots()
ax.fill(x, y, zorder=10)
ax.grid(True, zorder=5)
plt.show()
14、日期刻度示例(dates模块)
您可以绘制日期数据,包括主要和次要刻度以及两种自定义刻度格式。
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbookyears = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')datafile = cbook.get_sample_data('goog.npy')
try:
r = np.load(datafile, encoding='bytes').view(np.recarray)
except TypeError:
r = np.load(datafile).view(np.recarray)fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)datemin = datetime.date(r.date.min().year, 1, 1)
datemax = datetime.date(r.date.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)# format the coords message box
def price(x):
return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()plt.show()
请参阅matplotlib.ticker
并matplotlib.dates
了解详细信息和用法。
15、对数图
函数semilogx()
, semilogy()
和 loglog()
简化了对数图的创建。
import numpy as np
import matplotlib.pyplot as pltplt.subplots_adjust(hspace=0.4)
t = np.arange(0.01, 20.0, 0.01)# log y axis
plt.subplot(221)
plt.semilogy(t, np.exp(-t/5.0))
plt.title('semilogy')
plt.grid(True)# log x axis
plt.subplot(222)
plt.semilogx(t, np.sin(2*np.pi*t))
plt.title('semilogx')
plt.grid(True)# log x and y axis
plt.subplot(223)
plt.loglog(t, 20*np.exp(-t/10.0), basex=2)
plt.grid(True)
plt.title('loglog base 2 on x')# with errorbars: clip non-positive values
ax = plt.subplot(224)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')x = 10.0**np.linspace(0.0, 2.0, 20)
y = x**2.0
plt.errorbar(x, y, xerr=0.1*x, yerr=5.0 + 0.75*y)
ax.set_ylim(ymin=0.1)
ax.set_title('Errorbars go negative')plt.show()
16、极图(Polar)
polar()
命令生成极地图。
import numpy as np
import matplotlib.pyplot as pltr = np.arange(0, 2, 0.01)
theta = 2 * np.pi * rax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
ax.set_rmax(2)
ax.set_rticks([0.5, 1, 1.5, 2]) # less radial ticks
ax.set_rlabel_position(-22.5) # get radial labels away from plotted line
ax.grid(True)ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()
17、自动图例(Legend)
legend()
命令自动生成图例,并带有与MATLAB兼容的图例布局命令。
import numpy as np
import matplotlib.pyplot as plt# Make some fake data.
a = b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]# Create plots with pre-defined labels.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c + d, 'k', label='Total message length')legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')
# Put a nicer background color on the legend.
legend.get_frame().set_facecolor('#00FFCC')plt.show()
18、数学表达式(Mathtext模块)
matplotlib内部mathtext引擎现在支持许多TeX表达式。mathtext模块使用FreeType 和DejaVu,BaKoMa计算机现代版或STIX 字体提供TeX风格的数学表达式。请参阅matplotlib.mathtext
模块了解更多详情。
from __future__ import print_function
import matplotlib.pyplot as plt
import os
import sys
import re
import gc# Selection of features following "Writing mathematical expressions" tutorial
mathtext_titles = {
0: "Header demo",
1: "Subscripts and superscripts",
2: "Fractions, binomials and stacked numbers",
3: "Radicals",
4: "Fonts",
5: "Accents",
6: "Greek, Hebrew",
7: "Delimiters, functions and Symbols"}
n_lines = len(mathtext_titles)# Randomly picked examples
mathext_demos = {
0: r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",1: r"$\alpha_i > \beta_i,\ "
r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
r"\ldots$",2: r"$\frac{3}{4},\ \binom{3}{4},\ \stackrel{3}{4},\ "
r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",3: r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",
4: r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",5: r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
r"\ldots$",6: r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",7: r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$"}def doall():
# Colors used in mpl online documentation.
mpl_blue_rvb = (191./255., 209./256., 212./255.)
mpl_orange_rvb = (202/255., 121/256., 0./255.)
mpl_grey_rvb = (51./255., 51./255., 51./255.)# Creating figure and axis.
plt.figure(figsize=(6, 7))
plt.axes([0.01, 0.01, 0.98, 0.90], facecolor="white", frameon=True)
plt.gca().set_xlim(0., 1.)
plt.gca().set_ylim(0., 1.)
plt.gca().set_title("Matplotlib's math rendering engine",
color=mpl_grey_rvb, fontsize=14, weight='bold')
plt.gca().set_xticklabels("", visible=False)
plt.gca().set_yticklabels("", visible=False)# Gap between lines in axes coords
line_axesfrac = (1. / (n_lines))# Plotting header demonstration formula
full_demo = mathext_demos[0]
plt.annotate(full_demo,
xy=(0.5, 1. - 0.59*line_axesfrac),
xycoords='data', color=mpl_orange_rvb, ha='center',
fontsize=20)# Plotting features demonstration formulae
for i_line in range(1, n_lines):
baseline = 1. - (i_line)*line_axesfrac
baseline_next = baseline - line_axesfrac*1.
title = mathtext_titles[i_line] + ":"
fill_color = ['white', mpl_blue_rvb][i_line % 2]
plt.fill_between([0., 1.], [baseline, baseline],
[baseline_next, baseline_next],
color=fill_color, alpha=0.5)
plt.annotate(title,
xy=(0.07, baseline - 0.3*line_axesfrac),
xycoords='data', color=mpl_grey_rvb, weight='bold')
demo = mathext_demos[i_line]
plt.annotate(demo,
xy=(0.05, baseline - 0.75*line_axesfrac),
xycoords='data', color=mpl_grey_rvb,
fontsize=16)for i in range(n_lines):
s = mathext_demos[i]
print(i, s)
plt.show()if '--latex' in sys.argv:
# Run: python mathtext_examples.py --latex
# Need amsmath and amssymb packages.
fd = open("mathtext_examples.ltx", "w")
fd.write("\\documentclass{article}\n")
fd.write("\\usepackage{amsmath, amssymb}\n")
fd.write("\\begin{document}\n")
fd.write("\\begin{enumerate}\n")for i in range(n_lines):
s = mathext_demos[i]
s = re.sub(r"(?<!\\)\$", "$$", s)
fd.write("\\item %s\n" % s)fd.write("\\end{enumerate}\n")
fd.write("\\end{document}\n")
fd.close()os.system("pdflatex mathtext_examples.ltx")
else:
doall()
Matplotlib的mathtext基础架构是一个独立的实现,不需要在您的计算机上安装TeX或任何外部软件包。请参阅编写数学表达式的教程。
19、数学文本的TeX渲染(usetex)
尽管matplotlib的内部数学渲染引擎非常强大,但有时您需要TeX。Matplotlib使用usetex选项支持对字符串进行外部TeX呈现。
import numpy as np
import matplotlib.pyplot as plt# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)plt.savefig('tex_demo')
plt.show()
20、EEG 演示(pbrain)
您可以将matplotlib嵌入到pygtk,wx,Tk或Qt应用程序中。这是一个名为pbrain的EEG查看器屏幕截图。
较低的轴用specgram()
绘制其中一个EEG通道的光谱图。
有关如何在不同工具包中嵌入matplotlib的示例,请参阅:
21、XKCD-风格草图
matplotlib支持绘制 xkcd 风格
。
import numpy as np
import matplotlib.pyplot as pltwith plt.xkcd():
# Based on "Stove Ownership" from XKCD by Randall Monroe
# http://xkcd.com/418/fig = plt.figure()
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.xticks([])
plt.yticks([])
ax.set_ylim([-30, 10])data = np.ones(100)
data[70:] -= np.arange(30)plt.annotate(
'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))plt.plot(data)
plt.xlabel('time')
plt.ylabel('my overall health')
fig.text(
0.5, 0.05,
'"Stove Ownership" from xkcd by Randall Monroe',
ha='center')# Based on "The Data So Far" from XKCD by Randall Monroe
# http://xkcd.com/373/fig = plt.figure()
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.bar([0, 1], [0, 100], 0.25)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks([0, 1])
ax.set_xlim([-0.5, 1.5])
ax.set_ylim([0, 110])
ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
plt.yticks([])plt.title("CLAIMS OF SUPERNATURAL POWERS")
fig.text(
0.5, 0.05,
'"The Data So Far" from xkcd by Randall Monroe',
ha='center')plt.show()
matplotlib之pyplot 学习示例的更多相关文章
- 数据分析与展示——Matplotlib基础绘图函数示例
Matplotlib库入门 Matplotlib基础绘图函数示例 pyplot基础图表函数概述 函数 说明 plt.plot(x,y,fmt, ...) 绘制一个坐标图 plt.boxplot(dat ...
- python: 使用matplotlib的pyplot绘制图表
工作中需要观察数据的变化趋势,用python写了一段小程序来用显示简单图表,分享出来方便有同样需求的人,matplotlib是个很不错的库. #!encode=utf8 from matplotlib ...
- osg学习示例之遇到问题四骨骼动画编译osgCal
osg学习示例之遇到问题四骨骼动画编译osgCal 转自:http://blog.csdn.net/wuwangrun/article/details/8239451 今天学到书<OpenSce ...
- 不学就吃亏的underscorejs类库学习示例 ——(集合篇)
underscorejs是一个很不错的类库,我的很多项目都引用了这个类库,的确可以带来很多方便. 记得我当初学的时候,看underscorejs的api是看的一知半解的,甚至不明白api里的conte ...
- zigbee学习:示例程序SampleApp中按键工作流程
zigbee学习:示例程序SampleApp中按键工作流程 本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 环境: 主机:WIN7 开发环境:IAR8. ...
- zigbee学习:示例程序SampleApp中通讯流程
zigbee学习:示例程序SampleApp中通讯流程 本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 参考链接: http://wjf88223.bl ...
- Markdown学习示例
Markdown学习示例 什么是Markdown Markdown是一种在web显示带样式风格文本的方式.你能通过它控制文本的字体样式.插入图片.插入列表等.通常,Markdown使用一些特殊的非字母 ...
- 大数据下基于Tensorflow框架的深度学习示例教程
近几年,信息时代的快速发展产生了海量数据,诞生了无数前沿的大数据技术与应用.在当今大数据时代的产业界,商业决策日益基于数据的分析作出.当数据膨胀到一定规模时,基于机器学习对海量复杂数据的分析更能产生较 ...
- python matplotlib.pyplot学习记录
matplotlib是python中很强大的绘图工具,在机器学习中经常用到 首先是导入 import matplotlib.pyplot as plt plt中有很多方法,记录下常用的方法 plt.p ...
随机推荐
- c3p0 连接池配置
C3P0 可使用properties 配置文件方式,将c3p0.properties放在classpath目录下,如果为WEB应用,放在WEB-INF\classes下 c3p0.properties ...
- linux下root用户和tarena用户vimrc配置
设置vim自动缩进,行号,tab键宽度 如果是root超级用户,他的主目录是: /root ,打开文件vim的配置文件.vimrc 如果是tarena用户,他的主目录是:/home/tarena 打开 ...
- Python-基本语法元素
#TempConvert.py TempStr = input("请输入带有符号的温度值: ") if TempStr[-1] in ['F', 'f']: C = (eval(T ...
- 【模板】非旋转Treap
Treap,也叫做树堆,是指有一个随机附加域满足堆的性质的二叉搜索树. 如果一棵二叉搜索树插入节点的顺序是随机的,那我们得到的二叉搜索树在大多数情况下是平衡的,期望高度是log(n). 但有些情况下我 ...
- ganlgia-rrdcached
一.介绍 rrdcached是一个高性能的RRD缓存守护进程,在不带来大量磁盘读/写文件i/o负荷的情况下,允许gmetad实例维护多个RRD文件.rrdcached可通过命令套接字控制,并且包含在大 ...
- Android第三方文件选择器:aFileChooser
Android第三方文件选择器:aFileChooser aFileChooser是Android平台上的一个第三方文件选择器,其在github上的项目主页是:https://github.co ...
- 清北学堂模拟赛d3t5 c
分析:其实就是一道数学题.如果以左下角的点为原点建立平面直角坐标系,那么点(b,a)是最容易卡住棺材的.我们求出棺材左边到点(b,a)的距离最小值,只有w小于等于这个最小值才能被拉过去.那么先求出左面 ...
- Oracle-统计数据库表数据总数量
create or replace procedure prc_table_count(p_flag out varchar2) AS TCOUNT number; SCOUNT number; CO ...
- 解决Linux ssh登录马上退出问题
纠结了非常久,最终找到解决方法: 把sshd_config文件里的UsePAM改成no就能够了
- ipcs命令学习
参考这篇 http://blog.csdn.net/pyjfoot/article/details/7989097 ipcs -m -s -q 分别对应集中ipc ipcs -l 显示limits: ...