Home > Blockchain >  How to make pandas DataFrame plot's appear at the right point in a Jupyter notebook?
How to make pandas DataFrame plot's appear at the right point in a Jupyter notebook?

Time:08-14

I have a Jupyter notebook with %matplotlib widget as the first line. The notebook contains several markdown cells providing a header structure and some explaining texts.

Also there I am generating some plots from pandas.DataFrames, which are grouped using dynamically generated sections.

Extracted (not executable in this way), it looks like:

%matplotlib widget

import pandas
from IPython.display import display_markdown

dictionary: dict[str, pandas.DataFrame] = {
    "DataFrame 1": pandas.util.testing.makeDataFrame(),
    "DataFrame 2": pandas.util.testing.makeDataFrame(),
}
group: str
dataframe: pandas.DataFrame
for group, dataframe in dictionary.items():
    display_markdown("## %s" % (group), raw=True)
    dataframe.plot()

However, when running the notebook, it first shows me all the created sub-sections and then, after the last one, all the plots.

How can I bring them in the intended order?

For the case that this is relevant: I am using the Jupyter extension of Visual Studio Code.

Minimal exeutable/ runnable example: https://colab.research.google.com/drive/1iTefKtR93MuzStgpNB3zIxx9S0pAhAO8#scrollTo=yRqBQywrCr7T

CodePudding user response:

You are seeing the plots last because of the way matplotlib and Jupyter interact. Modern Jupyter puts the plots generated in a cell as a separate entity. To interweave them with markdown produced in the course of looping as the code runs procedurally you can suppress the output using %

  • Related