我試圖通過色調操縱計數圖的陰影。這是我繪制的繪圖代碼和相應的繪圖:
ax = sns.countplot(
data=data, y='M_pattern', hue='HHFAMINC',
palette=color_palette, lw=0.5, ec='black',
)
plt.yticks(rotation=45, ha='right')
legend_labels, _ = ax.get_legend_handles_labels()
hatches = ['-', ' ', 'x', '\\']
# Loop over the bars
for i,thisbar in enumerate(bar.patches):
# Set a different hatch for each bar
thisbar.set_hatch(hatches[i])
plt.legend(
legend_labels, [
'Less than 10,000$ to 50,000$',
'50,000$ to 100,000$',
'100,000 to 150,000$',
'More than 150,000'
]
, title='Income categories'
)
plt.ylabel('Mandatory trip pattern')
plt.show()

是否有一種直接的方法來分別孵化每個收入類別?
uj5u.com熱心網友回復:
ax.containers包含每組條形的串列。要訪問單個條形,您可以先回圈遍歷containers,然后遍歷每個條形。enumerate強烈建議使用zip同時回圈遍歷兩個串列,而不是使用。
要重命名圖例條目,將 areplace放在色調列的元素上以確保值和長名稱之間的對應關系在資料集更新后保持不變。
這是一個使用 seaborn 的“提示”資料集的示例。這里3*hatch_pattern使孵化密度增加 3 倍。
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
data = sns.load_dataset('tips')
ax = sns.countplot(
data=data.replace({'day': {'Thur': 'Thursday', 'Fri': 'Friday', 'Sat': 'Saturday', 'Sun': 'Sunday'}}),
y='time', hue='day',
palette='Set2', lw=0.5, ec='black')
plt.yticks(rotation=45, ha='right')
hatches = ['-', ' ', 'x', '\\']
for hatch_pattern, these_bars in zip(hatches, ax.containers):
for this_bar in these_bars:
this_bar.set_hatch(3 * hatch_pattern)
ax.legend(loc='upper right', title='Days')
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/317802.html
標籤:Python matplotlib 海生
上一篇:影片多個影像系列的子圖
