如何一次更改多个子图的颜色?

how to change the colors of multiple subplots at once?

我正在遍历一堆包含各种测量结果的 CSV 文件。

每个文件可能来自 4 个不同数据源之一。

在每个文件中,我将数据合并到每月数据集中,然后将其绘制在 3x4 网格中。保存此图后,循环继续并对下一个文件执行相同操作。

这部分我已经弄清楚了,但是我想为图表添加一个视觉线索,以了解它是什么数据。据我了解(并尝试过)

plt.subplot(4,3,1)
plt.hist(Jan_Data,facecolor='Red')
plt.ylabel('value count')
plt.title('January')

确实有效,但是这样一来,我将不得不手动将 facecolor='Red' 添加到每 12 个子图中。在这种情况下循环遍历这些图是行不通的,因为我只希望 ylabel 用于最左边的图,而 xlabels 用于底行。

开头设置 facecolor
fig = plt.figure(figsize=(20,15),facecolor='Red')

不起作用,因为它现在只更改 20 x 15 图形的背景颜色,随后在我将它保存为 PNG 时被忽略,因为它只设置为屏幕输出。

那么,是否只有一个简单的 setthecolorofallbars='Red' 命令用于 plt.hist(…plt.savefig(… 我丢失了,或者我应该将其复制粘贴到所有十二个月?

x- 和 y-labels(当您使用循环时)的问题可以通过使用 plt.subplots 来解决,因为您可以单独访问每个轴。

import matplotlib.pyplot as plt
import numpy.random

# creating figure with 4 plots
fig,ax = plt.subplots(2,2)

# some data
data = numpy.random.randn(4,1000)

# some titles
title = ['Jan','Feb','Mar','April']

xlabel = ['xlabel1','xlabel2']
ylabel = ['ylabel1','ylabel2']

for i in range(ax.size):
    a = ax[i/2,i%2]
    a.hist(data[i],facecolor='r',bins=50)
    a.set_title(title[i])

# write the ylabels on all axis on the left hand side
for j in range(ax.shape[0]):
    ax[j,0].set_ylabel(ylabel[j])

# write the xlabels an all axis on the bottom
for j in range(ax.shape[1]):
    ax[-1,j].set_xlabel(xlabels[j])


fig.tight_layout()

所有不是常量的特征(如标题)都可以放入数组中并放置在适当的轴上。

您可以使用 mpl.rc("axes", color_cycle="red") 为所有轴设置默认颜色循环。

在这个小玩具示例中,我使用 with mpl.rc_context 块将 mpl.rc 的效果限制为仅块。这样您就不会破坏整个会话的默认参数。

import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np
np.random.seed(42)

# create some toy data
n, m = 2, 2
data = []
for i in range(n*m):
    data.append(np.random.rand(30))

# and do the plotting
with mpl.rc_context():
    mpl.rc("axes", color_cycle="red")
    fig, axes = plt.subplots(n, m, figsize=(8,8))
    for ax, d in zip(axes.flat, data):
        ax.hist(d)