从文本文件中绘制一串数字
Plotting a string of numbers from text file
我有一个文本文件 (m.txt)
,其中的数字格式为:
4.52987812069
3.71367858211
4.50621674483
5.17260331988
5.06400394036
etc
我想使用 matplotlib
绘制这些图,但是当我执行 所有 时,m.txt
中的所有数字都打印在 x 轴上的 0 上。我显然希望 m 中的每个值都沿 x 轴打印,从 0 开始到 len(m) - 1
.
结束
我知道我弄乱了 for 循环,但我无法使其正确输出。谢谢你的帮助。这是我的代码:
import matplotlib.pyplot as plt
with open("m.txt") as m:
for line in m:
m_float = map(float,line.split())
plt.plot(m_float,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,5])
plt.show()
import matplotlib.pyplot as plt
with open("m.txt") as m:
for index, line in enumerate(m):
m_float = map(float,line.strip())
plt.plot(index, m_float,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,5])
plt.show()
我将 split
替换为 strip
for clarity. Notice, that I added enumerate
以获取带有索引的数字。稍后我将它们传递给 plt.plot
。我移出了循环 xlabel
、ylabel
和 axis
调用,因为不需要在每次迭代时设置标签和轴属性,您只需执行一次即可。
您必须传递一系列值才能绘制。
import matplotlib.pyplot as plt
x=[]
with open("m.txt") as m:
for line in m:
m_float = float(line.split())
x.append(m_float)
plt.plot(x,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,6])
plt.show()
如果你使用 numpy.loadtxt
or numpy.genfromtxt
你可以在没有循环的情况下做到这一点,例如:
import matplotlib.pyplot as plt
import numpy as np
m_float=np.loadtxt('m.txt')
plt.plot(m_float,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,5])
plt.show()
我有一个文本文件 (m.txt)
,其中的数字格式为:
4.52987812069
3.71367858211
4.50621674483
5.17260331988
5.06400394036
etc
我想使用 matplotlib
绘制这些图,但是当我执行 所有 时,m.txt
中的所有数字都打印在 x 轴上的 0 上。我显然希望 m 中的每个值都沿 x 轴打印,从 0 开始到 len(m) - 1
.
我知道我弄乱了 for 循环,但我无法使其正确输出。谢谢你的帮助。这是我的代码:
import matplotlib.pyplot as plt
with open("m.txt") as m:
for line in m:
m_float = map(float,line.split())
plt.plot(m_float,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,5])
plt.show()
import matplotlib.pyplot as plt
with open("m.txt") as m:
for index, line in enumerate(m):
m_float = map(float,line.strip())
plt.plot(index, m_float,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,5])
plt.show()
我将 split
替换为 strip
for clarity. Notice, that I added enumerate
以获取带有索引的数字。稍后我将它们传递给 plt.plot
。我移出了循环 xlabel
、ylabel
和 axis
调用,因为不需要在每次迭代时设置标签和轴属性,您只需执行一次即可。
您必须传递一系列值才能绘制。
import matplotlib.pyplot as plt
x=[]
with open("m.txt") as m:
for line in m:
m_float = float(line.split())
x.append(m_float)
plt.plot(x,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,6])
plt.show()
如果你使用 numpy.loadtxt
or numpy.genfromtxt
你可以在没有循环的情况下做到这一点,例如:
import matplotlib.pyplot as plt
import numpy as np
m_float=np.loadtxt('m.txt')
plt.plot(m_float,'bo')
plt.ylabel('FLOC - % of line')
plt.xlabel('Sample Number')
plt.axis([-10,10,0,5])
plt.show()