AssertionError:不兼容的大小:参数'height'必须是长度5或标量

时间:2016-02-10 11:30:52

标签: python numpy matplotlib

我有一个json文件,我正在使用natsort反向排序,然后我想绘制一个“速度”的图形,但我收到一个错误。我现在也在这里包含了JSON文件。

"AssertionError: incompatible sizes: argument 'height' must be length 5 or scalar"

Traceback (most recent call last): File "new.py", line 71, in <module> visualize_type(sorted_waypoints) File "new.py", line 45, in visualize_type plt.bar(xlocations, counter.values()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matp‌​lotlib/pyplot.py", line 2515, in bar ret = ax.bar(left, height, width=width, bottom=bottom, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matp‌​lotlib/axes.py", line 4999, in bar nbars) 

代码:

import json
import datetime
import pprint
from operator import itemgetter
import natsort
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter



#path to gps data file in json format.
data_file = "waypoints.json"


def speed_ans(self, data_file):
    pass



def visualize_type(output):
    """Visualize data by category in a bar graph"""

    #This returns a dict where it sums the total per Category.
    counter = Counter(item["Speed"] for item in output)

    # Set the labels which are based on the keys of our counter.
    labels = tuple("Speed")

    # Set where the labels hit the x-axis
    xlocations = np.arange(len(labels)) + 0.5

    # Width of each bar
    width = 0.5

    # Assign data to a bar plot
    plt.bar(xlocations, counter.values(), width=width)

    # Assign labels and tick location to x- and y-axis
    plt.xticks(xlocations + width / 2, labels, rotation=90)
    plt.yticks(range(0, max(counter.values()), 5))

    # Give some more room so the labels aren't cut off in the graph
    plt.subplots_adjust(bottom=0.4)

    # Make the overall graph/figure larger
    plt.rcParams['figure.figsize'] = 12, 8

    # Save the graph!
    plt.savefig("Graph.png")

    plt.clf()



if __name__ == '__main__':
    with open(data_file) as f:
        waypoints = json.load(f)

    sorted_waypoints = natsort.natsorted(waypoints, key=itemgetter(*['Speed']), reverse = True)
    pprint.pprint(sorted_waypoints)

    visualize_type(sorted_waypoints)

waypoints.json文件:

[{
    "Latitude": 1.282143333,
    "Timestamp": 1434368770,
    "Speed": 7.696,
    "Longitude": 103.850785
}, {
    "Latitude": 1.282205,
    "Timestamp": 1434368771,
    "Speed": 7.233,
    "Longitude": 103.850806667
}, {
    "Latitude": 1.282205,
    "Timestamp": 1434368772,
    "Speed": 7.233,
    "Longitude": 103.850806667
}, {
    "Latitude": 1.282205,
    "Timestamp": 1434368773,
    "Speed": 7.444,
    "Longitude": 103.850806667
}, {
    "Latitude": 1.282261667,
    "Timestamp": 1434368774,
    "Speed": 6.933,
    "Longitude": 103.850833333
}]

1 个答案:

答案 0 :(得分:1)

我认为你对tuple()对字符串做了什么做了错误的假设:

tuple("Speed")
# returns ('S', 'p', 'e', 'e', 'd')

我想你想要:

labels = counter.keys()
相关问题