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

标签 python matplotlib

我正在尝试使用这个例子: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()

enter image description here

关于python - Matplotlib:同一轴上具有不同左右比例的两个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567516/

相关文章:

python - 在 centos 6.7 上安装 booktype

python - 如何在不使用全局变量的情况下影响 python 生成器 : time example

python - 如何将多行 python 脚本粘贴到 ConEmu 中?

python - 堆积条形图 - 从非数值项开始

python - Matplotlib:显示 numpy "sparse"数组 - 放大点?

python - 按组和虚拟代码分类变量转换长格式分类数据

python - 匹配python正则表达式中的括号

python - 停止 matplotlib 使用 Arial 字体

python - "bumpy-function"的 Matplotlib 3D-Surface 不起作用

Python matplotlib 每第 N 条不同的颜色