Home > front end >  How to access the point objects in a seaborn.pointplot figure?
How to access the point objects in a seaborn.pointplot figure?

Time:11-12

  • I want to extract the y-axis positions of the points in a figure created with seaborn.pointplot. I don't need to modify the objects, it's for an automated test.

  • For other plots (e.g. barplots) I have been able to extract this from axes.patches.

  • Have been muddling around in the axes.collections but want to know if there's a straightforward way to get the y-axis positions of the points.

    import random
    import seaborn as sns
    import pandas as pd
    
    data = pd.DataFrame(
        {"Col1": ["A", "B", "C"]*10,
         "Col2": [random.uniform(1.0, 200.0) for _ in range(30)],
         "Col3": ["X"]*10   ["Y"]*10   ["Z"]*10
         }
    )
    params = {
        "x": "Col1",
        "y": "Col2",
        "data": data,
        "hue": "Col3",
        "color": "black",
        "dodge": 0.53333,
        "join": False
    }
    ax = sns.pointplot(**params)
    

CodePudding user response:

In this case, you can loop through ax.collections. There will be 3 collections, one for each hue. They are of type PathCollection. .get_offsets() gives their xy positions.

Here is some example code that draws a red circle around the extracted positions.

import random
import seaborn as sns
import pandas as pd

data = pd.DataFrame({"Col1": ["A", "B", "C"] * 10,
                     "Col2": [random.uniform(1.0, 200.0) for _ in range(30)],
                     "Col3": ["X"] * 10   ["Y"] * 10   ["Z"] * 10})
params = {"x": "Col1", "y": "Col2", "data": data, "hue": "Col3", "color": "black", "dodge": 0.53333, "join": False}
ax = sns.pointplot(**params)
for path in ax.collections:
    points = path.get_offsets()
    print(f"hue: {path.get_label()}; y-values: {points[:, 1]}")
all_x_values = [path.get_offsets()[:, 0] for path in ax.collections]
all_y_values = [path.get_offsets()[:, 1] for path in ax.collections]

ax.scatter(x=all_x_values, y=all_y_values, s=200, fc='none', ec='r')

sns.pointplot with extracted positions

hue: X; y-values: [126.22035010280258 141.12294652228957 77.11286110373693]
hue: Y; y-values: [99.68997767038964 58.52959793955581 154.63078569762334]
hue: Z; y-values: [90.76316340021354 71.05228738206348 68.13109019572413]
  • Related