Build labelled Python charts and export them as image files.

Before starting: Python lists and numeric values.

Practice project: Extend the examples into a small Matplotlib study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Matplotlib: draw a labelled line chart

    A Figure holds the drawing and an Axes holds a plotted coordinate system. Match x and y values by position, and label what the numbers mean.

    Python 3 with Matplotlib installed; save as chart.py and run python chart.py. A display backend is needed for show().

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [20, 35, 30], marker="o")
    ax.set(xlabel="Practice day", ylabel="Minutes", title="Study time")
    plt.show()
    Check the output
    A line connects (1,20), (2,35), and (3,30) with labelled axes.

    Add day 4 and 40 minutes to the two lists.

  2. Matplotlib: save a chart to an image

    savefig exports the figure. Saving before closing it also works in scripts without an interactive window when a non-interactive backend is selected.

    Python 3 with Matplotlib installed; save as chart.py and run python chart.py. A display backend is needed for show().

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    ax.bar(["SQL", "Web"], [3, 5])
    ax.set(ylabel="Completed lessons", title="Practice summary")
    fig.savefig("study-summary.png", dpi=150, bbox_inches="tight")
    plt.close(fig)
    Check the output
    Creates study-summary.png with bars of heights 3 and 5 in the working directory.

    Change the values and check that the exported image updates.

Open the Matplotlib learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.