在使用matplotlib构建一些绘图时,我无法解决这个(看起来很容易)的问题。在
我有表示范围内整数的灰度颜色(0-255-更高的数字意味着更暗),在这个示例中可以简化df:colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89],
'color4': [123], 'color5': [220], 'color6': [100],
'color7': [123], 'color8': [247], 'color9': [255]})
现在,通过循环,我想用以下颜色更改绘图背景:
^{pr2}$
通过使用matplotlib documentation我只能使用以下颜色格式:Matplotlib recognizes the following formats to specify a color:an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5)
or (0.1, 0.2, 0.5, 0.3));
a hex RGB or RGBA string (e.g., '#0F0F0F' or
'#0F0F0F0F');
a string representation of a float value in [0, 1]
inclusive for gray level (e.g., '0.5'); one of {'b', 'g', 'r', 'c',
'm', 'y', 'k', 'w'};
a X11/CSS4 color name;
a name from the xkcd color
survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue');
one of
{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',
'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} which
are the Tableau Colors from the ‘T10’ categorical palette (which is
the default color cycle);
a “CN” color spec, i.e. 'C' followed by a
single digit, which is an index into the default property cycle
(matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at
artist creation time and defaults to black if the cycle does not
include color.
使用这些SO答案:
已转换为重写代码:def rgb_int2tuple(rgbint):
return (rgbint // 256 // 256 % 256, rgbint // 256 % 256, rgbint % 256)
colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89], 'color4': [123],
'color5': [220], 'color6': [100], 'color7': [123], 'color8': [247], 'color9': [255]})
fig, ax = plt.subplots(3, 3, figsize=(10, 10), sharey='row', sharex='col')
fig.subplots_adjust(hspace=0, wspace=0)
column = 0
for i in range(3):
for j in range(3):
color = colors.iloc[0, column]
color = 255 - color
Blue, Green, Red = rgb_int2tuple(color)
print(f'{i}, {j}: {color}\t{Blue}{Green}{Red}')
ax[i, j].set_facecolor((Blue/255, Green/255, Red/255))
column += 1
但结果是:
这让我进入第1步,如何让python知道我的0-255刻度是灰色的。在
[编辑]:
我又读了一遍matplotlib.colors文件和发现a string representation of a float value in [0, 1]
inclusive for gray level (e.g., '0.5');
使用这个:
重写我的代码:colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89], 'color4': [123],
'color5': [220], 'color6': [100], 'color7': [123], 'color8': [247], 'color9': [255]})
fig, ax = plt.subplots(3, 3, figsize=(10, 10), sharey='row', sharex='col')
fig.subplots_adjust(hspace=0, wspace=0)
column = 0
for i in range(3):
for j in range(3):
color = colors.iloc[0, column]
color = 255 - color
color = color / 255
ax[i, j].set_facecolor(str(color))
column += 1
这给了我:
但我怀疑,这是最好的解决办法。在