【问题标题】:Matplotlib: two plots on the same axes with different left right scalesMatplotlib:同一轴上具有不同左右比例的两个图
【发布时间】:2016-02-23 02:07:47
【问题描述】:

我正在尝试使用此示例: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 命令,但显然没有。我该怎么做?

【问题讨论】:

  • 错误似乎不是源自twinx,当它们被传递给绘图函数时,它似乎位于xnp.arange(data)。我会检查以确保他们输出您期望的内容。

标签: python matplotlib


【解决方案1】:

试试

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(*) 所做的事情 也适用于嵌套的可迭代对象。但是,您应该首先使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多