http://blog.csdn.net/pipisorry/article/details/37766161
绘制文件中的数据Plotting data contained in files
从Ascii文件中读取数据 Reading data from ascii files
读取文件的方法很多,这里只介绍一种简单的方法,更多的可以参考官方文档和NumPy快速处理数据(文件存取)。
numpy的loadtxt方法可以直接读取文本数据到numpy二维数组
import numpy as np
import pylab as pl
# Use numpy to load the data contained in the file
# ’fakedata.txt’ into a 2-D array called data
data = np.loadtxt(’fakedata.txt’)
# plot the first column as x, and second column as y
pl.plot(data[:,0], data[:,1], ’ro’)
pl.xlabel(’x’)
pl.ylabel(’y’)
pl.xlim(0.0, 10.)
pl.show()[ Python文件输入输出详解]
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Cursor t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2 * np.pi * t) plt.plot(t, s1) Cursor(plt.gca(), horizOn=False, color='r', lw=1) #horizOn=True时,两个坐标都有显示光标 plt.show()结果示图(随着光标的移动,在图中x坐标上会画一条竖线,并在下方显示坐标):
绘制LaTeX数学公式
the start and the end of a mathtext string is $
在python raw string需要r‘’,表示不转义
Matlplotlib对LaTeX有一定的支持,如果记得使用raw字符串语法会很自然:
xlabel(r" x2y4 ")
在matplotlib里面,可以使用LaTex的命令来编辑公式,只需要在字符串前面加一个“r”即可
Here is a simple example:
# plain text
plt.title('alpha > beta')
produces “alpha > beta”.
Whereas this:
produces "".
一个简单的例子
import matplotlib.pyplot as plt
x = arange(1,1000,1)
r = -2
c = 5
y = [5*(a**r) for a in x]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.loglog(x,y,label = r" y=12σ21,c=5,σ1=−2 ")
ax.legend()
ax.set_xlabel(r"x")
ax.set_ylabel(r"y")
这实际上是一个power-law的例子。
[用Python做科学计算]Note:
1. matplotlib.rcParams属性字典,想要它正常工作,在matplotlibrc配置文件中需要设置text.markup = "tex"。
2. 如果你希望图表中所有的文字(包括坐标轴刻度标记)都是LaTeX'd,需要在matplotlibrc中设置text.usetex = True。如果你使用LaTeX撰写论文,那么这一点对于使图表和论文中其余部分保持一致是很有用的。
[LaTeX科技排版][参考文献自动搜集管理完美攻略(图文版):Latex+Lyx+Zotero]
一个更大的例子
In [6]: ax.text(2, 8, r"$ \mu \alpha \tau \pi \lambda \omega \tau \lambda \iota \beta $");
In [7]: ax.text(2, 6, r"$ \lim_{x \rightarrow 0} \frac{1}{x} $");
In [8]: ax.text(2, 4, r"$ a \ \leq \ b \ \leq \ c \ \Rightarrow \ a \ \leq \ c$");
In [9]: ax.text(2, 2, r"$ \sum_{i=1}^{\infty}\ x_i^2$");
In [10]: ax.text(4, 8, r"$ \sin(0) = \cos(\frac{\pi}{2})$");
In [11]: ax.text(4, 6, r"$ \sqrt[3]{x} = \sqrt{y}$");
In [12]: ax.text(4, 4, r"$ \neg (a \wedge b) \Leftrightarrow \neg a \vee \neg b$");
In [13]: ax.text(4, 2, r"$ \int_a^b f(x)dx$");
在实际中,我们可能经常会用到对数坐标轴,这时可以用下面的三个函数来实现
ax.semilogx(x,y) #x轴为对数坐标轴
ax.semilogy(x,y) #y轴为对数坐标轴
ax.loglog(x,y) #双对数坐标轴
matplotlib latex官方教程:
Writing mathematical expressions
Text rendering With LaTeX
ref:fxjwind