我正在尝试使用Matplotlib绘制一些测量数据。 使用下面显示的代码,我得到了绘图窗口和gui,但没有绘制绘图。如果我将绘图类型改为圆形或十字形,它就可以正常工作。
# coding=utf-8
import matplotlib.pyplot as plt
import csv
with open("AgPVP8.2.171g1L#2.csv") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
frequencies = []
phases = []
for row in reader:
frequency = float(row[0])
phase = float(row[4])
frequencies.append(frequency)
phases.append(phase)
plt.plot([frequencies], [phases], "b-")
plt.xscale("log")
plt.show()
答案 0 :(得分:1)
问题是频率和阶段仅存在于with open(...
的范围内,您必须将其置于此范围内:
import matplotlib.pyplot as plt
import csv
with open("AgPVP8.2.171g1L#2.csv") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
frequencies = []
phases = []
for row in reader:
frequency = float(row[0])
phase = float(row[4])
frequencies.append(frequency)
phases.append(phase)
plt.plot(frequencies, phases, "-b")
plt.xscale("log")
plt.show()
答案 1 :(得分:0)
plt.plot(x,y)
要求x
和y
为列表(或一般序列)或数组。
在这里,您试图绘制列表列表,即[x]
与x
不同。
因此,在您的代码中,您需要将plt.plot([frequencies], [phases], "b-")
替换为
plt.plot(frequencies, phases, "-b")
完整的代码应如下所示:
import matplotlib.pyplot as plt
import csv
with open("AgPVP8.2.171g1L#2.csv") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
frequencies = []
phases = []
for row in reader:
frequency = float(row[0])
phase = float(row[4])
frequencies.append(frequency)
phases.append(phase)
plt.plot(frequencies, phases, "b-")
plt.xscale("log")
plt.show()
我建议您查看numpy.loadtxt
或numpy.genfromtxt
。两者都可以在csv文件中更容易阅读,例如在这种情况下
import matplotlib.pyplot as plt
import numpy as np
frequencies, phases = np.loadtxt("AgPVP8.2.171g1L#2.csv", unpack=True, usecols = (0,4), delimiter=",")
plt.plot(frequencies, phases, "b-")
plt.xscale("log")
plt.show()