Skip to main content
 首页 » 编程设计

python之Matplotlib:同一轴上具有不同左右比例的两个图

2024年10月24日11bluestorm

我正在尝试使用这个例子: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(*) does 也适用于嵌套的迭代器。但是,您应该首先使用 int() 或 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()