如何使用子图在matplotlib中实现自动颜色更改

如何使用子图在matplotlib中实现自动颜色更改

本文介绍了如何使用子图在matplotlib中实现自动颜色更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib绘制图表。当我使用以下代码在同一图表上绘制它时:

  def draw0(x,ys,标签):


plt.suptitle(大标题)

i = 0 y中y的

plt.plot(x,y,label = labels [i])
plt.scatter(x,y)#点
plt.xticks(range(1,max(x)+ 1))
plt.grid(True)
i + = 1

plt.figlegend(loc =左上)

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]

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

一切正常。


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:
        plt.plot(x, y, label=labels[i])
        plt.scatter(x, y)  # dots
        plt.xticks(range(1, max(x) + 1))
        plt.grid(True)
        i+=1

    plt.figlegend(loc="upper left")

    plt.show()

    return

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]

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

everything works fine.charts in one windowBut i need each chart to be at the separate subplot.

I am trying to do it like this:

def draw11(x, ys, labels):

    plt.figure()

    plt.suptitle("big title")

    i =0
    for 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])
        plt.scatter(x, y)  # dots
        plt.xticks(range(1, max(x) + 1))
        plt.grid(True)
        i+=1

    plt.figlegend(loc="upper left")

    plt.show()

    return

I am getting this.

charts in sublots

Issue is that all charts have the same color. And legend is useless.How i can add automatic color management for all sublots? I'd like to have not the same colors there.Like subplot1.chart1 = color1, subplo1.chart2 = color2, sublot2.chart1 = color3, not color1.

解决方案

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"]()

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

    for ax, y, label in zip(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"])

这篇关于如何使用子图在matplotlib中实现自动颜色更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:55