Home>

I want to change the date display and specify the range of the graph.

Program syntax
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv ('test.csv')
data ["date and time"] = data ["date"] +''+ data ["time"]
print (type (data ["date and time"]))
dtypes = {'date and time':'str','maximum current':'int'}
parse_dates = ['date and time']
data2 = data [["Date and time", "WB1 maximum current", "WB2 maximum current", "WB3 maximum current", "WB4 maximum current"]]
df3 = data2.set_index ('date and time')
df3.plot ()
plt.xticks (rotation = 30)
plt.show ()
Be in trouble

The graph is output properly, but when I enter the date by specifying the range
(For example, from 00:00 on July 1, 2020 to 23:59 on July 2, 2020)

dfa = df3 ["2020/07/01 00:00": "2020/07/02 23:59"]
dfa.plot ()

I get a KeyError because there are no values ​​in the table.
With this method, you have to type in microseconds when specifying the range, so I would like to specify the range by changing the display to year/month/day hour: minute.

* About the date and time
The original csv data is divided into date and time, and if you do not add the date and time, the graph display will be strange, so this work is done.

Supplementary information (FW/tool version, etc.)

Usage environment: anaconda Spyder (Python3.8)

  • Answer # 1

    First, convert the date and time from a character string to a date (numeric) type so that the spacing on the horizontal axis can be expressed accurately.
    On top of thatqueryYou can narrow down the period by using.

    import pandas as pd
    from io import StringIO
    import matplotlib.pyplot as plt
    # test data
    s = "" "Date and time, Val
    2020-12-01 07: 15,1
    2020-12-01 12: 30,2
    2020-12-01 20:45,3
    2020-12-02 06: 10,4
    2020-12-02 11: 00,5
    2020-12-02 21:20,6
    2020-12-03 08: 00,7
    2020-12-03 13: 00,8 "" "
    df = pd.read_csv (StringIO (s))
    # Make it a date and time type (not the character type) and index it
    df ['date and time'] = pd.to_datetime (df ['date and time'])
    df.set_index ('date and time', inplace = True)
    df = df.query ('Date>= "2020-12-01 12:00" and Date<"2020-12-03"')
    print (df)
    "" "
                         Val
    Date and time
    2020-12-01 12:30:00 2
    2020-12-01 20:45:00 3
    2020-12-02 06:10:00 4
    2020-12-02 11:00:00 5
    2020-12-02 21:20:00 6
    "" "
    df.plot ()
    plt.xticks (rotation = 30)
    plt.show ()