Skip to content Skip to sidebar Skip to footer

How To Implement Automatic Color Change In Matplotlib With Subplots?

I am drawing charts with matplotlib. When i am drawing it at the same chart with this code: def draw0(x, ys, labels): plt.suptitle('big title') i =0 for y in ys:

Solution 1:

Matplotlib has a built-in property cycler, which by default has 10 colors in it to cycle over. However those are cycled per axes. If you want to cycle over subplots you would need to use the cycler and get a new color from it for each subplot.

import matplotlib.pyplot as plt
colors = plt.rcParams["axes.prop_cycle"]()

defdraw11(x, ys, labels):
    fig, axes = plt.subplots(nrows=len(ys), sharex=True)
    fig.suptitle("big title")

    for ax, y, label inzip(axes.flat, ys, labels):
        # Get the next color from the cycler
        c = next(colors)["color"]

        ax.plot(x, y, label=label, color=c)
        ax.scatter(x, y, color=c)  # dots
        ax.set_xticks(range(1, max(x) + 1))
        ax.grid(True)

    fig.legend(loc="upper left")
    plt.show()


x = [1,2,3,4,5]
y1 = [1,3,5,7,9]
y2 = [10,30,50,70,90]
y3 = [0.1,0.3,0.5,0.7,0.9]

draw11(x, [y1, y2, y3], ["chart1", "chart2", "chart3"])

enter image description here

Solution 2:

Just have a list of colors and select them for each plt.plot and plt.scatter.

colors = ['orange', 'cyan', 'green']
i =0for y in ys:
        if i == 0:
            ax = plt.subplot(len(ys),1, i+1)
        else:
            plt.subplot(len(ys), 1, i + 1, sharex=ax)
        plt.plot(x, y, label=labels[i], c=colors[i])
        plt.scatter(x, y, c=colors[i])  # dots
        plt.xticks(range(1, max(x) + 1))
        plt.grid(True)
        i+=1

Post a Comment for "How To Implement Automatic Color Change In Matplotlib With Subplots?"