pandas 如何在 Seaborn 点图上获取数据标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37106828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:12:04  来源:igfitidea点击:

How to get data labels on a Seaborn pointplot?

pythonpandasmatplotlibscipyseaborn

提问by lostsoul29

I have two arrays like so:

我有两个这样的数组:

Soldier_years = [1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864, 1865, 1866, 1867, 1868, 1869, 1870]
num_records_yob = [7, 5, 8, 9, 15, 17, 23, 19, 52, 55, 73, 73, 107, 137, 65, 182, 228, 257, 477, 853, 2303]

I'm trying to get these into a Seaborn pointplot like so:

我正在尝试将这些放入 Seaborn 点图,如下所示:

%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="darkgrid")

f, (ax) = plt.subplots(figsize=(12, 6), sharex=True)

sns.set_style("darkgrid")
ax = sns.pointplot(x=Soldier_years, y=num_records_yob)

I get a pointplot like so:

我得到一个像这样的点图:

Pointplot

点图

This plot is almost what I want. How do I get the data labels of each of the points to show above the respective points?

这个情节几乎是我想要的。如何获取每个点的数据标签以显示在相应点上方?

I tried ax.patches, but it is empty.

我试过ax.patches,但它是空的。

I'm trying to get it look like this (but for the pointplot): enter image description here

我试图让它看起来像这样(但对于点图): 在此处输入图片说明

回答by MaxU

you can do it this way:

你可以这样做:

[ax.text(p[0], p[1]+50, p[1], color='g') for p in zip(ax.get_xticks(), num_records_yob)]

plot

阴谋

回答by borgr

For future reference that will want a more general answer I suggest this code:

为了将来需要更一般答案的参考,我建议使用以下代码:

ymin, ymax = ax.get_ylim()
color="#3498db" # choose a color
bonus = (ymax - ymin) / 50 # still hard coded bonus but scales with the data
for x, y, name in zip(X, Y, names):
    ax.text(x, y + bonus, name, color=color)

Note that I also changed the comprehension to a for loop, I think it is more readable that way (when the list is actually thrown away)

请注意,我还将理解更改为 for 循环,我认为这样更具可读性(当列表实际上被丢弃时)