[英]Add percentages to histograms in JointGrid
Is it possible to add percentages to the histograms of a JointGrid?是否可以在 JointGrid 的直方图中添加百分比?
I could live with percentages below, in or above the bars.我可以接受低于、在条形图内或高于条形图的百分比。 Or with an extra axis showing the percentages + lines.
或者使用一个额外的轴显示百分比 + 线。 I went through the source code of the JointGrid to find a way to get the hidden axis of both histograms back so I could add percentages to those.
我浏览了 JointGrid 的源代码以找到一种方法来获取两个直方图的隐藏轴,以便我可以为它们添加百分比。
I also tried different labels for the histogram axises, but that doesn't work as they are shared:我还为直方图轴尝试了不同的标签,但这在共享时不起作用:
hex.ax_marg_y.set_yticklabels(["test", "label"])
This is my work in progress:这是我正在进行的工作:
labels = ['Ma 13', 'Di 14', 'Wo 15', 'Do 16', 'Vr 17', 'Za 18', 'Zo 19', 'Ma 20']
hex = sns.JointGrid(x, y, height = 12)
hex.ax_marg_x.hist(x, bins=np.arange(-0.5, 23.5))
hex.ax_marg_y.hist(y, bins=np.arange(-0.5, len(labels) + 0.5), orientation="horizontal")
hex.plot_joint(sns.kdeplot, shade=True, cmap="Blues", bw=.11)
plt.ylim(-0.5, len(labels)-0.5)
plt.xlim(-0.5, 23.5)
hex.ax_joint.set_xticks(range(24))
hex.ax_joint.set_yticks(range(len(labels)))
hex.ax_joint.set_yticklabels(labels)
plt.subplots_adjust(left=0.05, right=0.95, top=0.93, bottom=0) # Shrink figure so the legende is visible
hex.x = x2
hex.y = y2
hex.plot_joint(plt.scatter, marker = 'x', c = 'r', s = 190)
plt.show()
If you take care of saving a reference to the artists returned by ax_marg_{x|y}.hist()
, then it's just a matter of looping over each one and annotating at the right place:如果您负责保存对
ax_marg_{x|y}.hist()
返回的艺术家的引用,那么只需循环遍历每个艺术家并在正确的位置进行注释即可:
tips = sns.load_dataset("tips")
x = tips['total_bill']
y = tips['tip']
hex = sns.JointGrid(x, y)
_,_,bars_x = hex.ax_marg_x.hist(x)
_,_,bars_y = hex.ax_marg_y.hist(y, orientation="horizontal")
hex.plot_joint(sns.kdeplot, shade=True, cmap="Blues")
# annotate top hist
total_height = np.sum([bar.get_height() for bar in bars_x])
for bar in bars_x:
height = bar.get_height()
hex.ax_marg_x.annotate('{:.1f}%'.format(100*height/total_height),
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 1), # 1 points vertical offset
textcoords="offset points",
ha='center', va='bottom', fontsize=8)
# annotate right hist
total_height = np.sum([bar.get_width() for bar in bars_y])
for bar in bars_y:
height = bar.get_width()
hex.ax_marg_y.annotate('{:.1f}%'.format(100*height/total_height),
xy=(height, bar.get_y(), ),
xytext=(1, 10), # 1 points vertical offset
textcoords="offset points",
ha='left', va='center', fontsize=8)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.