【问题标题】:Plot only works when hard coded or Copy/Pasted绘图仅在硬编码或复制/粘贴时有效
【发布时间】:2016-06-05 19:56:59
【问题描述】:

更新 2 完整错误代码:

Traceback (most recent call last):
  File "C:\Users\Desktop\Radar2.py", line 156, in <module>
    radar = ComplexRadar(fig1, variables, ranges)
  File "C:\Users\Desktop\Radar2.py", line 127, in __init__
    num=n_ordinate_levels)
  File "C:\Python27\lib\site-packages\numpy\core\function_base.py", line 90, in linspace
    start = start * 1.
TypeError: can't multiply sequence by non-int of type 'float'

这个问题有一段时间了,如果有人可以帮助我解决问题,我将不胜感激。

在我的主代码中使用下面的Book1.csv 文件时,如果从另一个文件复制和粘贴数据,我似乎遇到了不存在的问题。我发现这与数据结构有关,但我正在努力寻找一种方法让它在主代码中接受它。

Player,P1,P1,Min,Max,,,
Team,T1,T2,N/A,N/A,,,
Season,2014/15,2015/16,N/A,N/A,,,
Age,25,27,N/A,N/A,,,
Var1,1,1,0.001,12,,,Var4
Var2,2,2,0.001,12,,,Var3
Var3,3,3,0.001,12,,,Var2
Var4,4,4,0.001,12,,,Var1
Var5,5,5,0.001,12,,,Var12
Var6,5.5,5.5,0.001,12,,,Var11
Var7,6.6,6.6,0.001,12,,,Var10
Var8,7.7,7.7,0.001,12,,,Var9
Var9,8.8,8.8,0.001,12,,,Var8
Var10,9.9,9.9,0.001,12,,,Var7
Var11,4.2,4.2,0.001,12,,,Var6
Var12,12,12,0.001,12,,,Var5

这是我的代码。我的错误当前指出“TypeError:不能将序列乘以'float'类型的非整数”。我需要将其保留为浮点数,因为我需要保留转换为 Int 时会丢失的小数点。

import matplotlib.pyplot as plt
import numpy as np
import Image

tup1, tup2, data, variables, ranges = [], [], [], [], []

with open('Book1.csv') as f:
    content = f.read().splitlines()    
    data.append(content[7].split(',')[1])
    variables.append(content[7].split(',')[0])    
    tup1.append(content[7].split(',')[3])
    tup2.append(content[7].split(',')[4])

    data.append(content[6].split(',')[1])
    variables.append(content[6].split(',')[0])
    tup1.append(content[6].split(',')[3])
    tup2.append(content[6].split(',')[4])

    data.append(content[5].split(',')[1])
    variables.append(content[5].split(',')[0])
    tup1.append(content[5].split(',')[3])
    tup2.append(content[5].split(',')[4])

    data.append(content[4].split(',')[1])
    variables.append(content[4].split(',')[0])
    tup1.append(content[4].split(',')[3])
    tup2.append(content[4].split(',')[4])

    data.append(content[15].split(',')[1])
    variables.append(content[15].split(',')[0])
    tup1.append(content[15].split(',')[3])
    tup2.append(content[15].split(',')[4])

    data.append(content[14].split(',')[1])
    variables.append(content[14].split(',')[0])
    tup1.append(content[14].split(',')[3])
    tup2.append(content[14].split(',')[4])

    data.append(content[13].split(',')[1])
    variables.append(content[13].split(',')[0])
    tup1.append(content[13].split(',')[3])
    tup2.append(content[13].split(',')[4])

    data.append(content[12].split(',')[1])
    variables.append(content[12].split(',')[0])
    tup1.append(content[12].split(',')[3])
    tup2.append(content[12].split(',')[4])

    data.append(content[11].split(',')[1])
    variables.append(content[11].split(',')[0])
    tup1.append(content[11].split(',')[3])
    tup2.append(content[11].split(',')[4])

    data.append(content[10].split(',')[1])
    variables.append(content[10].split(',')[0])
    tup1.append(content[10].split(',')[3])
    tup2.append(content[10].split(',')[4])

    data.append(content[9].split(',')[1])
    variables.append(content[9].split(',')[0])
    tup1.append(content[9].split(',')[3])
    tup2.append(content[9].split(',')[4])

    data.append(content[8].split(',')[1])
    variables.append(content[8].split(',')[0])
    tup1.append(content[8].split(',')[3])
    tup2.append(content[8].split(',')[4])


    Name = content[0].split(',')[1]
    Team = content[1].split(',')[1]
    Season = content[2].split(',')[1]
    Age = content[3].split(',')[1]

    data = [float(i) for i in data]
    ranges = zip(tup1, tup2)
    variables = variables

##variables = ['Var4', 'Var3', 'Var2', 'Var1', 'Var12', 'Var11', 'Var10', 'Var9', 'Var8', 'Var7', 'Var6', 'Var5']
##data = [4.0, 3.0, 2.0, 1.0, 12.0, 4.2, 9.9, 8.8, 7.7, 6.6, 5.5, 5.0]
##ranges = [(0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12), (0.001, 12)]

def _invert(x, limits):
    """inverts a value x on a scale from
    limits[0] to limits[1]"""
    return limits[1] - (x - limits[0])

def _scale_data(data, ranges):
    """scales data[1:] to ranges[0],
    inverts if the scale is reversed"""
    for d, (y1, y2) in zip(data[1:], ranges[1:]):
        assert (y1 <= d <= y2) or (y2 <= d <= y1)
    x1, x2 = ranges[0]
    d = data[0]
    if x1 > x2:
        d = _invert(d, (x1, x2))
        x1, x2 = x2, x1
    sdata = [d]
    for d, (y1, y2) in zip(data[1:], ranges[1:]):
        if y1 > y2:
            d = _invert(d, (y1, y2))
            y1, y2 = y2, y1
        sdata.append((d-y1) / (y2-y1) 
                     * (x2 - x1) + x1)
    return sdata

class ComplexRadar():
    def __init__(self, fig, variables, ranges,
                 n_ordinate_levels=7):
        angles = np.arange(0, 360, 360./len(variables))

        axes = [fig.add_axes([0.1,0.1,0.9,0.9],polar=True, axisbg='#ffffff',
                label = "axes{}".format(i))
                for i in range(len(variables))]
        l, text = axes[0].set_thetagrids(angles, 
                                         labels=variables, weight='semibold')
        [txt.set_rotation(angle-90) for txt, angle 
             in zip(text, angles)]
        for ax in axes[1:]:
            ax.patch.set_visible(False)
            ax.grid("off")
            ax.grid(False)
            ax.xaxis.set_visible(False)

        for i, ax in enumerate(axes):
            grid = np.linspace(*ranges[i], 
                               num=n_ordinate_levels)
            gridlabel = ["{}".format(round(x,2)) 
                         for x in grid]
            if ranges[i][0] > ranges[i][1]:
                grid = grid[::-1]
            gridlabel[0] = ""
            ax.set_rgrids(grid, labels=gridlabel, ha="center", va="center",
                         angle=angles[i], weight='semibold', fontsize=8, color='#333333')
            ax.spines["polar"].set_visible(False)
            ax.set_ylim(*ranges[i])
            theta = np.linspace(0., 2*np.pi, 80, endpoint=True)
        # THE LINE BELOW IS CAUSING THE PROBLEMS

        # variables for plotting
        self.angle = np.deg2rad(np.r_[angles, angles[0]])
        self.ranges = ranges
        self.ax = axes[0]
        self.ax.yaxis.grid(False)
    def plot(self, data, *args, **kw):
        sdata = _scale_data(data, self.ranges)
        self.ax.plot(self.angle, np.r_[sdata, sdata[0]], *args, **kw)
    def fill(self, data, *args, **kw):
        sdata = _scale_data(data, self.ranges)
        self.ax.fill(self.angle, np.r_[sdata, sdata[0]], *args, **kw)



# plotting
fig1 = plt.figure(figsize=(10, 10))
radar = ComplexRadar(fig1, variables, ranges)
radar.plot(data, color='#0000e6', linewidth=1)
radar.fill(data, alpha=0.4, color='#0000e6')
plt.savefig('radar-chart2.png',orientation='landscape',bbox_inches='tight',pad_inches=.8)  

如果您需要有关此问题的更多信息,请告诉我。

【问题讨论】:

  • 请始终添加完整的错误跟踪,而不仅仅是错误的名称。
  • 已更新错误。有什么想法吗?
  • 有人有什么想法吗?
  • 引发异常的代码是'start = start * 1'。但这不会发生在您共享的内容中。请分享完整代码,以便我们提供帮助。
  • 它发生在 numpy 内部...您需要发布 FULL TRACEBACK!!

标签: python python-2.7 numpy matplotlib


【解决方案1】:

错误在这一行:

for i, ax in enumerate(axes):
    grid = np.linspace(*ranges[i], 
                       num=n_ordinate_levels)

这是因为当您从文件中读取这些元素时,ranges 中的元素不是浮点数/整数:

ranges
Out[24]: 
[('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12'),
 ('0.001', '12')]

这基本上意味着您不应该将字符串传递给np.linspace。您可以通过添加将它们转换为数字的行来解决它:

data = [float(i) for i in data]
ranges = zip(tup1, tup2)
ranges = [(float(r[0]), int(r[1])) for r in ranges] #this is the added line

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多