From 71b714ab7d1a2a46d127ba462535f14ca9b8fbb3 Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Sun, 16 Jul 2023 16:17:45 +1000 Subject: [PATCH] Implement HorizontalEffectPlot --- yli/__init__.py | 2 +- yli/graphs.py | 161 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 1 deletion(-) diff --git a/yli/__init__.py b/yli/__init__.py index 55b9574..8a69d66 100644 --- a/yli/__init__.py +++ b/yli/__init__.py @@ -18,7 +18,7 @@ from .bayes_factors import bayesfactor_afbf from .config import config from .descriptives import auto_correlations, auto_descriptives from .distributions import beta_oddsratio, beta_ratio, hdi, transformed_dist -from .graphs import init_fonts +from .graphs import init_fonts, HorizontalEffectPlot from .io import pickle_read_compressed, pickle_read_encrypted, pickle_write_compressed, pickle_write_encrypted from .regress import IntervalCensoredCox, Logit, OLS, OrdinalLogit, PenalisedLogit, Poisson, regress, vif from .sig_tests import anova_oneway, auto_univariable, chi2, mannwhitney, pearsonr, spearman, ttest_ind, ttest_ind_multiple diff --git a/yli/graphs.py b/yli/graphs.py index 9c2b7a1..99585c3 100644 --- a/yli/graphs.py +++ b/yli/graphs.py @@ -1,3 +1,21 @@ +# scipy-yli: Helpful SciPy utilities and recipes +# Copyright © 2022–2023 Lee Yingtong Li (RunasSudo) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +from collections import namedtuple + def init_fonts(): import matplotlib.pyplot as plt @@ -5,3 +23,146 @@ def init_fonts(): plt.rcParams['text.latex.preamble'] = r'\usepackage{tgheros}\usepackage{newtxmath}' plt.rcParams['font.size'] = 11 plt.rcParams['figure.dpi'] = 100 + +EffectPlotData = namedtuple('EffectPlotData', ['y', 'mean', 'ci0', 'ci1', 'pvalue']) + +class EffectPlotText: + def __init__(self, y, text, skip_width=False, **kwargs): + self.y = y + self.text = text + self.skip_width = skip_width + self.kwargs = kwargs + +class HorizontalEffectPlot: + # TODO: Documentation + + def __init__(self, measure_name, xlabel, *, header_y=1): + self.measure_name = measure_name + self.xlabel = xlabel + + self.text_left = [[]] # [EffectPlotText] + #self.text_right = [[], [], [], [], [], [], []] # [EffectPlotText] + self.text_right = [[], [], [], [], [], []] # [EffectPlotText] + self.data = [] + + #self.space_right = [0.15, 0.05, 0, 0, 0.1, 0, 0] # Space in inches between each right text column + self.space_right = [0.15, 0.05, 0, 0, 0.1, 0] # Space in inches between each right text column + + # Add headings + self.text_right[0].append(EffectPlotText(header_y, measure_name, skip_width=True, ha='center', fontweight='medium')) + self.text_right[2].append(EffectPlotText(header_y, '(95% CI)', skip_width=True, ha='center', fontweight='medium')) + self.text_right[5].append(EffectPlotText(header_y, 'p', skip_width=True, ha='center', fontweight='medium', fontstyle='italic')) + + def add_nobar(self, y, label, mean=None, ci0=None, ci1=None, pvalue=None): + # Label + self.text_left[0].append(EffectPlotText(y, label, ha='right')) + + # Mean + if mean is not None: + self.text_right[0].append(EffectPlotText(y, mean, ha='right')) + + # Confidence intervals + if ci0 is not None: + self.text_right[1].append(EffectPlotText(y, '({}'.format(ci0), ha='right')) + self.text_right[2].append(EffectPlotText(y, '–', ha='left')) + self.text_right[3].append(EffectPlotText(y, '{})'.format(ci1), ha='left')) + + # P value and flag + if pvalue is not None: + self.text_right[5].append(EffectPlotText(y, pvalue, ha='right')) + + def add_bar(self, y, label, mean, ci0, ci1, pvalue): + self.data.append(EffectPlotData(y=y, mean=mean, ci0=ci0, ci1=ci1, pvalue=pvalue)) + + # Label + self.text_left[0].append(EffectPlotText(y, label, ha='right')) + + # Mean + self.text_right[0].append(EffectPlotText(y, '{:.2f}'.format(mean), ha='right')) + + # Confidence intervals + self.text_right[1].append(EffectPlotText(y, '({:.2f}'.format(ci0), ha='right')) + self.text_right[2].append(EffectPlotText(y, '–', ha='left')) + self.text_right[3].append(EffectPlotText(y, '{:.2f})'.format(ci1), ha='left')) + + # P value and flag + if pvalue < 0.0005: + self.text_right[4].append(EffectPlotText(y, '<', ha='left')) + self.text_right[5].append(EffectPlotText(y, '0.001*', ha='left')) + elif pvalue < 0.01: + self.text_right[5].append(EffectPlotText(y, '{:.3f}*'.format(pvalue), ha='left')) + elif pvalue < 0.05: + self.text_right[5].append(EffectPlotText(y, '{:.2f}*'.format(pvalue), ha='left')) + else: + self.text_right[5].append(EffectPlotText(y, '{:.2f}'.format(pvalue), ha='left')) + #if pvalue < 0.05: + # self.text_right[6].append(EffectPlotText(y, '*', ha='left')) + + def add_group_heading(self, y, label): + self.text_left[0].append(EffectPlotText(y, label, ha='right', fontweight='medium')) + + def _width_of(self, text): + txt = self.ax.text(9999, 9999, text, in_layout=False, transform=self.ax.transAxes) + txt_width_px = txt.get_window_extent(renderer=self.fig.canvas.get_renderer()).width + txt_width_in = self.fig.dpi_scale_trans.inverted().transform([txt_width_px, 0])[0] + txt.remove() + return txt_width_in + + def render( + self, + width=4, + xscale='log', xlim=(0.5, 4), xticks=['0.5', '1', '2', '4'], minorticks=[], + ): + import matplotlib.pyplot as plt + + fig_height = 0.3 * max(d.y for d in self.data) + 0.2 + + self.fig, self.ax = plt.subplots(figsize=(width, fig_height)) + if xscale == 'log': + self.ax.axvline(1, color='grey', linewidth=1) + else: + self.ax.axvline(0, color='grey', linewidth=1) + + self.ax.set_xscale(xscale) + self.ax.set_xlim(*xlim) + self.ax.set_xticks([float(x) for x in xticks]) + self.ax.set_xticks(minorticks, minor=True) + self.ax.set_xticklabels(xticks) + self.ax.set_xticklabels([], minor=True) + self.ax.set_xlabel(self.xlabel) + + self.ax.set_ylim(-max(d.y for d in self.data) - 1, 0) + self.ax.set_yticks([]) + + # Render data bars + for data in self.data: + self.ax.errorbar(x=[data.mean], y=[-data.y], xerr=[[data.mean-data.ci0], [data.ci1-data.mean]], fmt='o', color='C0', capsize=4, capthick=1.5) + + # Left text + tmp = self.fig.dpi_scale_trans.inverted().transform(self.ax.transAxes.transform([0, 0])) + tmp[0] -= 0.15 + x = self.ax.transAxes.inverted().transform(self.fig.dpi_scale_trans.transform(tmp))[0] + + for text in self.text_left[0]: + y = self.ax.transAxes.inverted().transform(self.ax.transData.transform([1, -text.y]))[1] + self.ax.text(x, y, text.text, transform=self.ax.transAxes, va='center_baseline', **text.kwargs) + + # Get width of right columns + widths_right = [max(self._width_of(t.text) if not t.skip_width else 0 for t in col) if len(col) > 0 else 0 for col in self.text_right] + + # Right text + for i, col in enumerate(self.text_right): + for text in col: + tmp = self.fig.dpi_scale_trans.inverted().transform(self.ax.transAxes.transform([1, 0])) + tmp[0] += sum(self.space_right[0:i+1]) + tmp[0] += sum(widths_right[0:i]) or 0 + + if text.kwargs['ha'] == 'center': + tmp[0] += widths_right[i] / 2 + if text.kwargs['ha'] == 'right': + tmp[0] += widths_right[i] + + x = self.ax.transAxes.inverted().transform(self.fig.dpi_scale_trans.transform(tmp))[0] + y = self.ax.transAxes.inverted().transform(self.ax.transData.transform([1, -text.y]))[1] + + self.ax.text(x, y, text.text, transform=self.ax.transAxes, va='center_baseline', **text.kwargs)