pythonmatplotlibgis

Saving subplots in matplotlib as separate images


I am trying to save the six subplots I have created into separate image files. I can only get it to save the first subplot. How do I get it to save all 6 separately?

Here is my code:

# define the colors
color_palette = [{"Neon": "#ff0099",  "Background": "#2e002e"},
                 {"Neon": "#00ff00",  "Background": "#003300"},
                 {"Neon": "#00ccff",  "Background": "#002233"},
                 {"Neon": "#ffff00",  "Background": "#333300"},
                 {"Neon": "#ff6600",  "Background": "#331a00"},
                 {"Neon": "#ff00ff",  "Background": "#330033"}
]

# visualize networks
for idx, (city, edges) in enumerate(city_edges.items()):   

    # set the plot paramts
    neon = color_palette[idx]['Neon']
    color_bcg  = color_palette[idx]['Background']
    width = 0.5

    # do the plot
    f, ax = plt.subplots(1,1,figsize=(12,12))
    edges.plot(ax = ax, color = neon, linewidth = width, alpha = 0.9)
    ax.set_facecolor(color_bcg)

    # get rid of the ticks
    for xlabel_i in ax.get_xticklabels(): xlabel_i.set_visible(False)
    for ylabel_i in ax.get_yticklabels(): ylabel_i.set_visible(False)
    for tick in ax.get_xticklines(): tick.set_visible(False)
    for tick in ax.get_yticklines(): tick.set_visible(False)

    # add the title
    ymin, ymax = plt.ylim()
    extension = 0.1 * (ymax - ymin)
    ax.set_ylim(ymin, ymax + extension)
    ax.set_title(city, fontsize = 20, color = neon, y = 0.9)

plt.savefig("cities.png")

Solution

  • You have to call savefig inside the loop and use a unique figure name!

        f.savefig(f"cities{idx}.png")