plot x-axis as date in matplotlib

后端 未结 2 1281
傲寒
傲寒 2020-12-02 02:33

I am trying to perform some analysis on data. I got csv file and I convert it into pandas dataframe. the data looks like this. Its has several columns, but I am trying to dr

2条回答
  •  余生分开走
    2020-12-02 02:47

    Set the index to the datetime series

    If you set the index to the datetime series matplotlib will handle the x axis for you. Here is a minimal example of how you might deal with this visualization.

    Simple example:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    date_time = ["2011-09-01", "2011-08-01", "2011-07-01", "2011-06-01", "2011-05-01"]
    date_time = pd.to_datetime(date_time)
    temp = [2, 4, 6, 4, 6]
    
    DF = pd.DataFrame()
    DF['temp'] = temp
    DF = DF.set_index(date_time)
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.3)
    plt.xticks(rotation=90)
    plt.plot(DF)
    

    This will yield a plot that looks like the following:

    Setting the index makes things easier

    The important note is that setting the DataFrame index to the datetime series allows matplotlib to deal with x axis on time series data without much help.

    Follow this link for detailed explanation on spacing axis ticks (specifically dates)

提交回复
热议问题