我正在使用 Seaborn 在 Python 中創建條形圖。我有一個 2(注意:分開 vs 專注)X 3(解決方案:1,2,3)設計。對于分割,我希望條形顏色為深紅色、深綠色、深藍色。為了集中注意力,我希望條形顏色為紅色、綠色、藍色。
此代碼不起作用,因為調色板僅適用于hue引數:
import seaborn as sns
import matplotlib.pyplot as plt
data = sns.load_dataset('attention')
palette = ["darkred", "red", "darkgreen", "green", "darkblue", "blue"]
palette = ["darkred", "darkgreen", "darkblue", "red", "green", "blue"]
sns.set(style='ticks', context='notebook', font_scale=1.2)
fig, ax = plt.subplots(figsize=(7, 5), dpi=96)
my_plot = sns.barplot(x="solutions", y="score", hue="attention",
palette=palette, capsize=.1, ax=ax, data=data)
plt.show()

這段代碼幾乎有效:
import seaborn as sns
import matplotlib.pyplot as plt
data = sns.load_dataset('attention')
sns.set(style='ticks', context='notebook', font_scale=1.5)
fig, ax = plt.subplots(figsize=(7, 5), dpi=96)
sns.barplot(x="solutions", y="score",
palette=['red', 'green', 'blue'], capsize=.1, ax=ax,
data=data.query('attention=="focused"'))
sns.barplot(x="solutions", y="score",
palette=['darkred', 'darkgreen', 'darkblue'], capsize=.1, ax=ax,
data=data.query('attention=="divided"'))
sns.despine(top=True, right=True)
plt.tight_layout()
plt.show()
但有兩個問題:
- 沒有傳說
- 酒吧沒有分開。

必須(應該?)有某種方式以優雅的方式用 seaborn 創造這個人物。第一種方法是理想的:使用指定圖形的引數對 barplot 進行一次呼叫。第二種方法沒問題:多次呼叫 barplot。租賃理想的方法將是直接的 matplotlib bar() 呼叫,但在這一點上,我會接受任何導致所需數字的方法。
請注意,據我所知,這些名稱相似的問題似乎并未解決此問題中尋求的結果:
要將所有變體放入圖例中,
TupleHandler可以使用 ,例如(使用colors=['crimson', 'limegreen', 'dodgerblue']):from matplotlib.legend_handler import HandlerTuple ax.legend(handles=[tuple(bar_group) for bar_group in ax.containers], labels=[bar_group.get_label() for bar_group in ax.containers], title=ax.legend_.get_title().get_text(), handlelength=4, handler_map={tuple: HandlerTuple(ndivide=None, pad=0.1)})
這是另一個例子:
data = sns.load_dataset('tips') sns.set(style='ticks', context='notebook', font_scale=1.2) fig, ax = plt.subplots(figsize=(12, 5)) sns.barplot(x="day", y="tip", hue="smoker", capsize=.1, ax=ax, data=data) for bar_group, desaturate_value in zip(ax.containers, [0.5, 1]): for bar, color in zip(bar_group, plt.cm.Set2.colors): bar.set_facecolor(sns.desaturate(color, desaturate_value)) ax.legend(handles=[tuple(bar_group) for bar_group in ax.containers], labels=[bar_group.get_label() for bar_group in ax.containers], title=ax.legend_.get_title().get_text(), handlelength=4, handler_map={tuple: HandlerTuple(ndivide=None, pad=0.1)}) sns.despine() plt.tight_layout() plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375377.html標籤:Python matplotlib 海生
