I cannot solve this (what seems easy) problem when using matplotlib to build some plots.
当使用matplotlib构建一些图时,我无法解决这个(似乎很容易)的问题。
I have gray scale colors represented as integers in range(0-255 - higher numbers meaning darker) which can be simplified in this example df:
我有灰度颜色表示范围内的整数(0-255 - 更高的数字意味着更暗),在本例df中可以简化:
colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89],
'color4': [123], 'color5': [220], 'color6': [100],
'color7': [123], 'color8': [247], 'color9': [255]})
Now by looping I want to change the plots background with those colors as:
现在通过循环我想用这些颜色更改绘图背景:
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]
print(f'{i}, {j}: {color}')
# here I used (0.15, 0.16, 0.17) as example.
#But I want to have variable "color" converted into readable color by set_facecolor
ax[i, j].set_facecolor((0.15, 0.16, 0.17))
column += 1
by using matplotlib documentation I can only do it in those colors formats:
通过使用matplotlib文档,我只能用这些颜色格式:
Matplotlib recognizes the following formats to specify a color:
Matplotlib识别以下格式以指定颜色:
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));
[0,1]中浮点值的RGB或RGBA元组(例如,(0.1,0.2,0.5)或(0.1,0.2,0.5,0.3));
a hex RGB or RGBA string (e.g., '#0F0F0F' or '#0F0F0F0F');
十六进制RGB或RGBA字符串(例如,'#0F0F0F'或'#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'};
[0,1]中浮点值的字符串表示,包括灰度级(例如,'0.5'); {'b','g','r','c','m','y','k','w'}之一;
a X11/CSS4 color name;
一个X11 / CSS4颜色名称;
a name from the xkcd color survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue');
来自xkcd颜色调查的名称;以'xkcd:'为前缀(例如,'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);
其中一个{'tab:blue','tab:orange','tab:green','tab:red','tab:purple','tab:brown','tab:pink','tab:grey' ,'tab:olive','tab:cyan'},它们是'T10'分类调色板中的Tableau颜色(这是默认的颜色循环);
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.
“CN”颜色规范,即“C”后跟一个数字,这是默认属性循环的索引(matplotlib.rcParams ['axes.prop_cycle']);索引在艺术家创建时发生,如果循环不包括颜色,则默认为黑色。
Using those SO answers:
使用那些SO答案:
- RGB Int to RGB - Python
- Converting a [0-255] integer range to a [0.0-1.0] float range
RGB Int到RGB - Python
将[0-255]整数范围转换为[0.0-1.0]浮点范围
I converted rewrote my code to:
我转换后将我的代码改写为:
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
但结果是:
Which takes me to step1, how to let python know that my 0-255 scale is gray.
带我到step1,如何让python知道我的0-255比例是灰色的。
[EDIT]:
I read again the matplotlib.colors documentation and found
我再次阅读matplotlib.colors文档并找到了
- a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5');
[0,1]中浮点值的字符串表示,包括灰度级(例如,'0.5');
using this:
I rewrote my code to:
我把我的代码重写为:
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
这给了我:
But I doubt, that this is the best solution.
但我怀疑,这是最好的解决方案。
1 个解决方案
#1
0
You may convert the number of a string which denotes the grey level between 0 and 1.
您可以转换表示0到1之间灰度级的字符串数。
import pandas as pd
import matplotlib.pyplot as plt
colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89], 'color4': [123],
'color5': [220], 'color6': [100], 'color7': [123], 'color8': [247], 'color9': [255]})
fig, axes = plt.subplots(3, 3, figsize=(10, 10), sharey='row', sharex='col')
fig.subplots_adjust(hspace=0, wspace=0)
for ax, c in zip(axes.flat, colors.T[0].values):
ax.set_facecolor(str(c/255.))
plt.show()
Or you may convert it to a RGB tuple, where each channel has the same value
或者您可以将其转换为RGB元组,其中每个通道具有相同的值
for ax, c in zip(axes.flat, colors.T[0].values):
ax.set_facecolor((c/255.,c/255.,c/255.))
Finally, you may use a colormap and normalization as
最后,您可以使用色彩映射和规范化
norm = plt.Normalize(0,255)
cmap = plt.get_cmap("gray")
for ax, c in zip(axes.flat, colors.T[0].values):
ax.set_facecolor(cmap(norm(c)))
You get the same result in all three cases.
在所有三种情况下,您都会得到相同的结果。
#1
0
You may convert the number of a string which denotes the grey level between 0 and 1.
您可以转换表示0到1之间灰度级的字符串数。
import pandas as pd
import matplotlib.pyplot as plt
colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89], 'color4': [123],
'color5': [220], 'color6': [100], 'color7': [123], 'color8': [247], 'color9': [255]})
fig, axes = plt.subplots(3, 3, figsize=(10, 10), sharey='row', sharex='col')
fig.subplots_adjust(hspace=0, wspace=0)
for ax, c in zip(axes.flat, colors.T[0].values):
ax.set_facecolor(str(c/255.))
plt.show()
Or you may convert it to a RGB tuple, where each channel has the same value
或者您可以将其转换为RGB元组,其中每个通道具有相同的值
for ax, c in zip(axes.flat, colors.T[0].values):
ax.set_facecolor((c/255.,c/255.,c/255.))
Finally, you may use a colormap and normalization as
最后,您可以使用色彩映射和规范化
norm = plt.Normalize(0,255)
cmap = plt.get_cmap("gray")
for ax, c in zip(axes.flat, colors.T[0].values):
ax.set_facecolor(cmap(norm(c)))
You get the same result in all three cases.
在所有三种情况下,您都会得到相同的结果。