y轴未在matplotlib

时间:2017-12-30 07:38:39

标签: python matplotlib plot

我有以下列表数据: 第一个元素是PM级别,第二个元素是日期。

[
['83', '89', '88', '86', '85', '83', '86', '85', '86', '89', '88', '89', 
 '90', '88', '85', '85', '84', '80', '85', '-', '103', '107', '104', '106']

['2017-12-29 15:00', '2017-12-29 16:00', '2017-12-29 17:00', '2017-12-29 18:00', 
 '2017-12-29 19:00', '2017-12-29 20:00', '2017-12-29 21:00', '2017-12-29 22:00',
 '2017-12-29 23:00', '2017-12-29 24:00', '2017-12-30 01:00', '2017-12-30 02:00', 
 '2017-12-30 03:00', '2017-12-30 04:00', '2017-12-30 05:00', '2017-12-30 06:00',
 '2017-12-30 07:00', '2017-12-30 08:00', '2017-12-30 09:00', '2017-12-30 11:00',
 '2017-12-30 12:00', '2017-12-30 13:00', '2017-12-30 14:00', '2017-12-30 15:00']]

这是我程序相关片段的一部分。

@app.route('/pm25')
def pm25_graph():
    data_list = Display.data_retrieval()
    pm10, pm25, dates = data_list
    fig = Figure(figsize=(12, 5), dpi=100)
    ax = fig.add_subplot(111, title="PM 25 Level")
    ax.plot_date(dates, pm25, '-')
    fig.autofmt_xdate()

    canvas = FigureCanvas(fig)
    png_output = BytesIO()
    canvas.print_png(png_output)
    response = make_response(png_output.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response

当我运行程序时,我得到了:

the graph that the y-axis values are not arranged by their values

请有人帮我解决这个问题。非常感谢提前。

1 个答案:

答案 0 :(得分:1)

您的y值是字符串,因此按字典顺序排序,即107由于前导80而小于1。您需要将它们转换为数字:

new_pm25 = []
for x in pm25:
    try:
        new_pm25.append(float(x))
    except ValueError:
        new_pm25.append(float('nan'))

现在你可以绘制:

ax.plot_date(dates, new_pm25, '-')

结果:

enter image description here