pythonpandasmatplotlib

How to line plot Pandas Dataframe as sub graphs?


I have a DataFrame that looks like this: {"1578286800000":71,"1578373200000":72,"1578459600000":72,"1578546000000":74,"1578632400000":7,"1578891600000":7,"1578978000000":6,"1579064400000":7,"1579150800000":6}

The format is: Datetime:int

I want to create sub graph out of the data like, graph one would be for the first 5 data pairs and graph two would be for the rest.

I've tried to graph the entire dataframe but keeps getting this error: ValueError: If using all scalar values, you must pass an index

As you can see the dataframe doesn't have an index, and I don't know how to specify Datetime as the x axis and int as the y axis.

Edit 1 (with code):

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_json("somedata.json")
df.plot.line()
plt.show()

somedata.json contains the same data as mentioned at the beginning of the question.

Edit 2:

with open('temp.json', 'r') as json_file:
data_pairs = json.load(json_file)

dataframe = pd.DataFrame.from_dict(data_pairs, orient='index')

fig, axes = plt.subplots(2, 1)
dataframe[0:5].plot(ax=axes[0], legend=False)
_ = plt.xticks(rotation=45)
dataframe[5:].plot(ax=axes[1], legend=False)
_ = plt.xticks(rotation=45)

Solution

  • You can create a dataframe (with one column) having the datetime as index by using the method from_dict() with orient='index'. Then you can use the plot() method from Pandas for a quick drawing of the data divided in 2 parts:

    df = pd.DataFrame.from_dict({"1578286800000":71,"1578373200000":72,"1578459600000":72,"1578546000000":74,
                                 "1578632400000":7,"1578891600000":7,"1578978000000":6,"1579064400000":7,"1579150800000":6},
                                orient='index')
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7,4))
    df[:5].plot(ax=ax1)
    df[5:].plot(ax=ax2)
    plt.show()
    

    plot