Home > Software design >  Show previously created pandas plot
Show previously created pandas plot

Time:07-07

Say I create a bar plot in a Jupyter notebook:

import pandas as pd
import matplotlib.pyplot as plt

speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ["snail", "pig", "elephant", "rabbit", "giraffe", "coyote", "horse"]
df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index)

plot = df.plot(kind='bar', stacked=True)

This shows my chart.

enter image description here

Then, in the next cell, I make a modification, e.g. adding data labels:

for bar in plot.patches:
    height = bar.get_height()
    width = bar.get_width()
    x = bar.get_x()
    y = bar.get_y()
    label_text = height
    label_x = x   width / 2
    label_y = y   height / 2
    if label_text != 0:
        plot.text(
            label_x,
            label_y,
            int(label_text),
            ha="center",
            va="center",
            color="white",
            fontweight="bold",
        )

Now, how can I show the plot again? plt.show() returns nothing.

CodePudding user response:

Just show the figure again:

plot.figure

enter image description here

As an alternative, you can use plot.get_figure().

  • Related