0

I made some regression plots with FacetGrid/lmplot and would like to add regression coefficients, p values etc. to each subplot. However the annotations show up in weird places (s. picture) and I don't exactly understand how to work with the axes object that is returned by lmplot so it's just trial and error which did not lead to a solution. Reading this https://matplotlib.org/stable/api/axes_api.html did not clarify things.

enter image description here

I would appreciate it if someone could 1) point me to an explanation how to access/manipulate/loop through the subplots in general (via the axes object?) or 2) how to fix my code to put the annotations into the right place.

Code for plots:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import matplotlib as mpl
from scipy.stats import pearsonr

T = pd.read_csv('T.csv',sep=',')
g = sns.lmplot(data=T, y='Score', x='Value', col='MPM', row='Test', y_partial='Age',
               sharex=False, sharey=False) 

r, p = stats.pearsonr(T.Value, T.Score)

for ax in g.axes.flat:
    ax.text(0, 0, "p={}, R={}".format(p,r), horizontalalignment='left', 
            verticalalignment='bottom',size='medium', color='black', weight='semibold')

The plots turn out the same when I use this:

g = sns.FacetGrid(data=T, col='MPM', sharex=False, sharey=False)
g.map_dataframe(sns.regplot, data=T_age, y='Score', x='Value', y_partial='Age')
            

I tried moving the annotations by entering something > 0 for the coordinates in ax.text(x, y,...) but I get the error "Image size of 99693x1170 pixels is too large. It must be less than 2^16 in each direction."

Example data here: https://github.com/TanjaS91/Example_data/tree/main

RBG
  • 69
  • 1
  • 5
  • The text in the annotations in your image does not match correspond to what your code would produce. Are you sure that you have provided an example that can reproduce the problem? – mwaskom Feb 04 '22 at 11:43
  • Yes I'm sure, I just took a screenshot of the plot when the annotation said "An annotation p, r" and then changed it in the code but everything else is the same. The example data are also just a toy example with the same structure but much less data points – RBG Feb 04 '22 at 12:17
  • 1
    You probably want to use "axes coordinates" to position your text. Default, "data coordinates" are used. See [matplotlib's transformation tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html). So, maybe try something like `ax.text(0.02, 0.02, ..., transform=ax.transAxes)`. Apart from that, the rest of your code looks to use the correct approach. – JohanC Feb 04 '22 at 12:27

0 Answers0