我有以下图表 chart
我需要获取图例中每个类别的颜色。例如,我需要知道Twitter平台使用的颜色。 我使用
检索图例的文本legend=ax.get_legend()
legend.texts
但是我仍然需要知道颜色
答案 0 :(得分:1)
让我提出以下建议:如果您指定要用于绘图的调色板和色相顺序,则可以使用它们也直接返回绘图中色相类别的颜色。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(42)
df = pd.DataFrame({"x" : ["Category"] * 30,
"y" : np.random.rand(30),
"hue" : np.random.choice(list("ABCDEFGHIJKL"), size=30)})
hues = df["hue"].unique()
palette = sns.husl_palette(len(hues), l=0.7)
sns.swarmplot(x="x", y="y", hue="hue", palette=palette, hue_order=hues, data=df)
输出
然后
# print the color of the letter 'B' in the plot
color = palette[list(hues).index("B")]
print(color)
为您提供RGB颜色
[0.21538975947324868, 0.7566005611127228, 0.3762755878794595]
或者,对于所有颜色
for hue, color in zip(hues, palette):
print("The color of '{}' is: {}".format(hue, color))
输出
The color of 'C' is: [0.9709009234187059, 0.5326413088101082, 0.6030946551014079]
The color of 'G' is: [0.9564746134064298, 0.5689330861555781, 0.21514455558380652]
The color of 'E' is: [0.7694979084301814, 0.6558708257601433, 0.21360096988729887]
The color of 'I' is: [0.5896986083607835, 0.7091177093811508, 0.21250650504472351]
The color of 'B' is: [0.21538975947324868, 0.7566005611127228, 0.3762755878794595]
The color of 'D' is: [0.22701819286983138, 0.7401655088143408, 0.632501836267289]
The color of 'L' is: [0.2350973175622082, 0.7278659021357948, 0.7570948140143763]
The color of 'J' is: [0.24712600818727698, 0.708085275229765, 0.9105299070653927]
The color of 'H' is: [0.6214187468312122, 0.6348139081106288, 0.9644867235044855]
The color of 'A' is: [0.874677664347576, 0.53077533058416, 0.9640932638014564]
The color of 'F' is: [0.9675513199127449, 0.5048915449454215, 0.8037781860187498]