绘图仅在硬编码或复制/粘贴时有效

时间:2016-06-05 19:56:59

标签: python python-2.7 numpy matplotlib

更新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

这是我的代码。我的错误目前正在说明&#34; TypeError:不能将序列乘以非类型&#39; float&#39;&#34;。我需要保持它作为一个浮点数,因为我需要保留小数点,如果转换为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)  

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

1 个答案:

答案 0 :(得分:0)

错误在这一行:

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
相关问题