如何在 Seaborn 点图上获取数据标签?
How to get data labels on a Seaborn pointplot?
我有两个这样的数组:
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]
我正在尝试像这样将它们放入 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)
我得到了这样的点图:
这个剧情几乎就是我想要的。如何让每个点的数据标签显示在各自的点上方?
我试过ax.patches
,但它是空的。
我试图让它看起来像这样(但对于点图):
你可以这样做:
[ax.text(p[0], p[1]+50, p[1], color='g') for p in zip(ax.get_xticks(), num_records_yob)]
为了将来需要更一般性答案的参考,我建议使用以下代码:
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)
请注意,我还将推导式更改为 for 循环,我认为这样更具可读性(当列表实际上被丢弃时)
我有两个这样的数组:
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]
我正在尝试像这样将它们放入 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)
我得到了这样的点图:
这个剧情几乎就是我想要的。如何让每个点的数据标签显示在各自的点上方?
我试过ax.patches
,但它是空的。
我试图让它看起来像这样(但对于点图):
你可以这样做:
[ax.text(p[0], p[1]+50, p[1], color='g') for p in zip(ax.get_xticks(), num_records_yob)]
为了将来需要更一般性答案的参考,我建议使用以下代码:
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)
请注意,我还将推导式更改为 for 循环,我认为这样更具可读性(当列表实际上被丢弃时)