Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

python - Why pyplot(matplotlib) is joining points randomly?

Why is pyplot joining points randomly when I run this code?

def plot_date_value(single_data_frame):
    date_axis_data = []
    value_axis_data = []
    date_ticks = []
    for item in single_data_frame:
        date_axis_data.append(date2num(item[0]))
        date_ticks.append(item[0])
        value_axis_data.append(item[1])
        print(item[0], '---------------------', item[1])

    fig = plt.figure()
    graph = fig.add_subplot(111)
    graph.plot(date_axis_data, value_axis_data, 'r-o')
    graph.set_xticks(date_axis_data)
    graph.set_xticklabels([date.strftime("%Y-%m-%d %H:%M") for date in date_ticks])
    plt.show()

My data to this function is this:

[(datetime.datetime(2011, 9, 14, 6, 0), 0.83697607), (datetime.datetime(2011, 9, 14, 8, 0), 1.010857357), (datetime.datetime(2011, 9, 14, 10, 0), 0.982353533), (datetime.datetime(2011, 9, 14, 16, 0), 0.962431422), (datetime.datetime(2011, 9, 15, 20, 0), 0.971906937), (datetime.datetime(2011, 9, 16, 2, 0), 1.000917626), (datetime.datetime(2011, 9, 17, 2, 0), 0.827756728), (datetime.datetime(2011, 9, 14, 18, 0), 0.898688627), (datetime.datetime(2011, 9, 14, 20, 0), 0.978427012), (datetime.datetime(2011, 9, 15, 18, 0), 0.822463165), (datetime.datetime(2011, 9, 16, 16, 0), 1.222488219), (datetime.datetime(2011, 9, 16, 20, 0), 0.909770116), (datetime.datetime(2011, 9, 16, 22, 0), 1.121605357)]

The graph it spits out is this:

enter image description here

Why is this happening? Any help will be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It connects the points in the order given. Your dates are not sorted.

Try changing the for loop to:

    for item in sorted(single_data_frame):

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...