在 Python 的 seaborn 中重新排序堆叠的 histplot
Re-order stacked histplot in Python's seaborn
我使用 Python 的 seaborn
库和 histplot
函数来创建堆叠条形图。
这是我的数据和图表的示例:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
group = np.repeat(['G1', 'G2'], 4)
value = np.array(['1', '2', '3', '4', '1', '2', '3', '4'])
percentage = np.array([20, 10, 40, 30, 50, 25, 20, 5])
stacked = pd.DataFrame({'Group':group, 'Value':value, 'Percentage':percentage})
sns.histplot(stacked, x = 'Group', hue = 'Value', weights = 'Percentage', multiple = 'stack', palette = 'colorblind', shrink = 0.75)
plt.legend(labels = stacked['Value'].unique()[::-1], bbox_to_anchor = (1, 1), fontsize = 8)
我只想颠倒Value
的顺序,使蓝色部分 (1) 在底部,深橙色部分 (4) 在顶部.即,它的排序方式应与图例中的相同,并且颜色应保持不变(1 = 蓝色,2 = 浅橙色,依此类推)。不知何故,我无法创建这个。
非常感谢任何帮助!
您可以使用 invert_yaxis
并将 yticks
设置为 0 到 100,如下所示:
axe = sns.histplot(stacked, x = 'Group', hue = 'Value', weights = 'Percentage', multiple = 'stack', palette = 'colorblind', shrink = 0.75)
plt.legend(labels = stacked['Value'].unique()[::-1], bbox_to_anchor = (1, 1), fontsize = 8)
plt.gca().invert_yaxis()
plt.yticks(np.arange(0,100,20), np.arange(100,0,-20))
axe.margins(y=0)
plt.show()
如果添加这些行,您将得到以下输出:
我使用 Python 的 seaborn
库和 histplot
函数来创建堆叠条形图。
这是我的数据和图表的示例:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
group = np.repeat(['G1', 'G2'], 4)
value = np.array(['1', '2', '3', '4', '1', '2', '3', '4'])
percentage = np.array([20, 10, 40, 30, 50, 25, 20, 5])
stacked = pd.DataFrame({'Group':group, 'Value':value, 'Percentage':percentage})
sns.histplot(stacked, x = 'Group', hue = 'Value', weights = 'Percentage', multiple = 'stack', palette = 'colorblind', shrink = 0.75)
plt.legend(labels = stacked['Value'].unique()[::-1], bbox_to_anchor = (1, 1), fontsize = 8)
我只想颠倒Value
的顺序,使蓝色部分 (1) 在底部,深橙色部分 (4) 在顶部.即,它的排序方式应与图例中的相同,并且颜色应保持不变(1 = 蓝色,2 = 浅橙色,依此类推)。不知何故,我无法创建这个。
非常感谢任何帮助!
您可以使用 invert_yaxis
并将 yticks
设置为 0 到 100,如下所示:
axe = sns.histplot(stacked, x = 'Group', hue = 'Value', weights = 'Percentage', multiple = 'stack', palette = 'colorblind', shrink = 0.75)
plt.legend(labels = stacked['Value'].unique()[::-1], bbox_to_anchor = (1, 1), fontsize = 8)
plt.gca().invert_yaxis()
plt.yticks(np.arange(0,100,20), np.arange(100,0,-20))
axe.margins(y=0)
plt.show()
如果添加这些行,您将得到以下输出: