How to get data labels on a Seaborn pointplot?
Asked Answered
G

3

7

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:

%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.

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

Greenaway answered 9/5, 2016 at 2:0 Comment(0)
G
15

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

Giselagiselbert answered 9/5, 2016 at 12:11 Comment(0)
E
2

You can just superpose a barplot with transparent bars, and then use bar_label:

# create the bar plot only to generate the containers for the bar label
bp = sns.barplot(x=Soldier_years, y=num_records_yob, alpha=0)

# use the containers of the barplot to generate the labels
labels = ax.bar_label(bp.containers[0])

Full Example

import seaborn as sns
import matplotlib.pyplot as plt

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]

f, (ax) = plt.subplots(figsize=(12, 6))
sns.set_style("darkgrid")

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

# create the bar plot only to generate the containers for the bar label
bp = sns.barplot(x=Soldier_years, y=num_records_yob, alpha=0)

# use the containers of the barplot to generate the labels
labels = ax.bar_label(bp.containers[0])

enter image description here

Equip answered 1/11, 2022 at 8:51 Comment(0)
J
1

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)

Jayejaylene answered 18/2, 2018 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.