我正在尝试使用这个例子:http://matplotlib.org/examples/api/two_scales.html#api-two-scales 我自己的数据集如下所示:
import sys
import numpy as np
import matplotlib.pyplot as plt
print sys.argv
logfile = sys.argv[1]
data = []
other_data =[]
with open(logfile,'rb') as f:
for line in f:
a = line.split(',')
print a
data.append(a[1])
other_data.append(a[2][:-1])
print other_data
x = np.arange(0,len(data))
fig,ax1 = plt.subplots()
ax1.plot(x,np.arange(data))
ax2 = ax1.twinx()
ax2.plot(x,np.arange(other_data))
plt.show()
但是,我不断收到此错误:
'Traceback (most recent call last):
File "share/chart.py", line 17, in <module>
ax1.plot(x,np.arange(data))
TypeError: unsupported operand type(s) for -: 'list' and 'int'
我认为我正确使用 twinx 命令,但显然不是。我怎样才能做到这一点?
最佳答案
尝试
x1.plot(x,np.array(data)) # do you mean "array" here?
在这两个地方,而不是
x1.plot(x,np.arange(data))
但是你为什么要在这里使用任何东西呢?如果你只是
x1.plot(data)
它将自动生成您的 x 值,并且 matplotlib
将处理各种不同的可迭代对象,而无需转换它们。
您应该提供一个示例,其他人可以通过添加一些示例数据来立即运行。这也可以帮助您调试。它被称为 Minimal, Complete, and Verifiable Example .
您也可以删除一些脚本:
import matplotlib.pyplot as plt
things = ['2,3', '4,7', '4,1', '5,5']
da, oda = [], []
for thing in things:
a, b = thing.split(',')
da.append(a)
oda.append(b)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(da)
ax2.plot(oda)
plt.savefig("da oda") # save to a .png so you can paste somewhere
plt.show()
注释 1: matplotlib
默认为您生成 x 轴的值。如果你愿意的话,你可以把它们放进去,但这只是一个犯错误的机会。
注释 2: matplotlib
正在接受字符串,并将尝试为您转换为数值。
如果您想拥抱 Python,请使用列表理解,然后使用 zip(*)
- 这是 zip()
的逆操作:
import matplotlib.pyplot as plt
things = ['2,3', '4,7', '4,1', '5,5']
da, oda = zip(*[thing.split(',') for thing in things])
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(da)
ax2.plot(oda)
plt.savefig("da oda") # save to a .png so you can paste somewhere
plt.show()
但是,如果您真的很想使用数组,那么转置 - array.T
- 做什么 也适用于嵌套迭代。但是,您应该首先使用 zip(*)
doesint()
或 float()
转换为数值:
import matplotlib.pyplot as plt
import numpy as np
things = ['2,3', '4,7', '4,1', '5,5']
strtup = [thing.split(',') for thing in things]
inttup = [(int(a), int(b)) for a, b in strtup]
da, oda = np.array(inttup).T
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(da)
ax2.plot(oda)
plt.savefig("da oda")
plt.show()
关于python - Matplotlib:同一轴上具有不同左右比例的两个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567516/