4
绘制文件中的数据Plotting data contained in files
4.1
从Ascii文件中读取数据 Reading data from ascii files
读取文件的方法很多,这里只介绍一种简单的方法,更多的可以参考官方文档和NumPy快速处理数据(文件存取)。
numpy的loadtxt方法可以直接读取如下文本数据到numpy二维数组
**********************************************
# fakedata.txt
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
**********************************************
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()
4.2 写入数据到文件
Writing data to a text file
写文件的方法也很多,这里只介绍一种可用的写入文本文件的方法,更多的可以参考官方文档。
import numpy as np
# Let’s make 2 arrays (x, y) which we will write to a file
# x is an array containing numbers 0 to 10, with intervals of 1
x = np.arange(0.0, 10., 1.)
# y is an array containing the values in x, squared
y = x*x
print ’x = ’, x
print ’y = ’, y
# Now open a file to write the data to
# ’w’ means open for ’writing’
file = open(’testdata.txt’, ’w’)
# loop over each line you want to write to file
for i in range(len(x)):
# make a string for each line you want to write
# ’\t’ means ’tab’
# ’\n’ means ’newline’
# ’str()’ means you are converting the quantity in brackets to a string type
txt = str(x[i]) + ’\t’ + str(y[i]) + ’ \n’
# write the txt to the file
file.write(txt)
# Close your file
file.close()
对LaTeX数学公式的支持
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")
程序执行结果如图3所示,这实际上是一个power-law的例子,有兴趣的朋友可以继续google之。
再看一个《用Python做科学计算》中的简单例子,下面的两行程序通过调用plot函数在当前的绘图对象中进行绘图:
plt.plot(x,y,label="sin(x)",color="red",linewidth=2)
plt.plot(x,z,"b--",label="cos(x2)")
plot函数的调用方式很灵活,第一句将x,y数组传递给plot之后,用关键字参数指定各种属性:
label:
给所绘制的曲线一个名字,此名字在图示(legend)中显示。只要在字符串前后添加"$"符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。
color: 指定曲线的颜色
linewidth:
指定曲线的宽度
详细的可以参考matplotlib教程:
matplotlib.rcParams属性字典
想要它正常工作,在matplotlibrc配置文件中需要设置text.markup = "tex"。
如果你希望图表中所有的文字(包括坐标轴刻度标记)都是LaTeX'd,需要在matplotlibrc中设置text.usetex =
True。如果你使用LaTeX撰写论文,那么这一点对于使图表和论文中其余部分保持一致是很有用的。
对数坐标轴
在实际中,我们可能经常会用到对数坐标轴,这时可以用下面的三个函数来实现
ax.semilogx(x,y)
#x轴为对数坐标轴
ax.semilogy(x,y)
#y轴为对数坐标轴
ax.loglog(x,y)
#双对数坐标轴