Home > Mobile >  Plotting multiple dataframes in one chart
Plotting multiple dataframes in one chart

Time:10-11

In the following code, in each iteration a dataframe is read from a dictionary and is plotted. My intention is see all plots in one chart, but I see multiple charts in separate windows.

def plot(my_dict):
    for key in my_dict:
        df = my_dict[key]
        df.plot.line(x='c', y='i')
    plt.show()

I see some tutorials about that, e.g. enter image description here

CodePudding user response:

Consider concatenating all data together to plot data frame once. Specifically, horizontally merge with pandas.concat on the c (i.e., shared x-axis variable), renaming i (i.e., y-axis and legend series) for each dict key, and then call DataFrame.plot only once:

def plot(my_dict):
    graph_df = pd.concat(
        [
            df[['c', 'i']].rename({'i': k}, axis=1).set_index('c')
            for k, df in my_dict.items()
        ],
        axis=1
     )

    graph_df.plot(kind="line")

    plt.show()

CodePudding user response:

Pandas uses enter image description here

Simplified Version

If you want a stripped down version of the plot function, you could write it like so:

def plot2(my_dict: dict):
    """Plot a dictionary of dataframes.

    Parameters
    ----------
    my_dict : dict
        Dictionary of dataframes.
    """
    plt.plot(*[[_df['c'], _df['i']] for _df in my_dict.values()])
    plt.show()

Example


import numpy as np
import pandas as pd


d = {
    char: pd.DataFrame(
        {"c": np.random.randint(0, 100, 20), "i": np.random.randint(0, 100, 20)}
    )
    for char in "abcdef"
}

plot2(d, 'c', 'i')

Output:

enter image description here

CodePudding user response:

According to these docs you can pass an matplotlib axes object to df.plot.line() (which passes it to df.plot(). I think something like this might work:

def plot(my_dict, axes_obj):
    for key in my_dict:
        df = my_dict[key]
        df.plot.line(x='c', y='i', ax=axes_obj)
    plt.show()

There are several ways to obtain an axes object, for example:

fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)

or to get the current axes:

plt.gca()
  • Related