Skip to content

Commit

Permalink
Credited help from GitHub user for jitter and edits to adjust table d…
Browse files Browse the repository at this point in the history
…elta values location and general plotter trimming
  • Loading branch information
JAnns98 committed Oct 9, 2024
1 parent 1c639f1 commit eae1792
Show file tree
Hide file tree
Showing 7 changed files with 191 additions and 146 deletions.
2 changes: 2 additions & 0 deletions dabest/_modidx.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@
'dabest/misc_tools.py'),
'dabest.misc_tools.extract_contrast_plotting_ticks': ( 'API/misc_tools.html#extract_contrast_plotting_ticks',
'dabest/misc_tools.py'),
'dabest.misc_tools.extract_group_summaries': ( 'API/misc_tools.html#extract_group_summaries',
'dabest/misc_tools.py'),
'dabest.misc_tools.get_color_palette': ('API/misc_tools.html#get_color_palette', 'dabest/misc_tools.py'),
'dabest.misc_tools.get_kwargs': ('API/misc_tools.html#get_kwargs', 'dabest/misc_tools.py'),
'dabest.misc_tools.get_params': ('API/misc_tools.html#get_params', 'dabest/misc_tools.py'),
Expand Down
67 changes: 63 additions & 4 deletions dabest/misc_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
__all__ = ['merge_two_dicts', 'unpack_and_add', 'print_greeting', 'get_varname', 'get_unique_categories', 'get_params',
'get_kwargs', 'get_color_palette', 'initialize_fig', 'get_plot_groups', 'add_counts_to_ticks',
'extract_contrast_plotting_ticks', 'set_xaxis_ticks_and_lims', 'show_legend',
'Gardner_Altman_Plot_Aesthetic_Adjustments', 'Cumming_Plot_Aesthetic_Adjustments', 'Redraw_Spines']
'Gardner_Altman_Plot_Aesthetic_Adjustments', 'Cumming_Plot_Aesthetic_Adjustments', 'Redraw_Spines',
'extract_group_summaries']

# %% ../nbs/API/misc_tools.ipynb 4
import datetime as dt
Expand Down Expand Up @@ -103,7 +104,6 @@ def get_params(effectsize_df, plot_kwargs):
plot_kwargs : dict
Kwargs passed to the plot function.
"""
dabest_obj = effectsize_df.dabest_obj
plot_data = effectsize_df._plot_data
xvar = effectsize_df.xvar
yvar = effectsize_df.yvar
Expand All @@ -112,8 +112,11 @@ def get_params(effectsize_df, plot_kwargs):
mini_meta = effectsize_df.mini_meta
effect_size = effectsize_df.effect_size
proportional = effectsize_df.proportional
results = effectsize_df.results
dabest_obj = effectsize_df.dabest_obj
all_plot_groups = dabest_obj._all_plot_groups
idx = dabest_obj.idx


if effect_size not in ["mean_diff", "delta_g"] or not delta2:
show_delta2 = False
Expand Down Expand Up @@ -159,9 +162,15 @@ def get_params(effectsize_df, plot_kwargs):
horizontal = plot_kwargs["horizontal"]
if horizontal:
float_contrast = False

# Contrast Axes kwargs
es_marker_size = plot_kwargs["es_marker_size"]
halfviolin_alpha = plot_kwargs["halfviolin_alpha"]
ci_type = plot_kwargs["ci_type"]

return (dabest_obj, plot_data, xvar, yvar, is_paired, effect_size, proportional, all_plot_groups, idx,
show_delta2, show_mini_meta, float_contrast, show_pairs, effect_size_type, group_summaries, err_color, horizontal)
show_delta2, show_mini_meta, float_contrast, show_pairs, effect_size_type, group_summaries, err_color, horizontal,
results, es_marker_size, halfviolin_alpha, ci_type)

def get_kwargs(plot_kwargs, ytick_color):
"""
Expand Down Expand Up @@ -1328,7 +1337,6 @@ def Cumming_Plot_Aesthetic_Adjustments(contrast_axes, reflines_kwargs, is_paired
A boolean flag to determine if the plot is for horizontal plotting.
"""


# If 0 lies within the ylim of the contrast axes, draw a zero reference line.
if horizontal:
contrast_axes_lim = contrast_axes.get_xlim()
Expand Down Expand Up @@ -1488,3 +1496,54 @@ def Redraw_Spines(rawdata_axes, contrast_axes, redraw_axes_kwargs, float_contras
for ax, xlim, ylim in zip([rawdata_axes, contrast_axes], [og_xlim_raw, og_xlim_contrast], [og_ylim_raw, og_ylim_contrast]):
ax.set_xlim(xlim)
ax.set_ylim(ylim)


def extract_group_summaries(proportional, err_color, rawdata_axes, asymmetric_side, horizontal,
bootstraps_color_by_group, plot_palette_raw, all_plot_groups,
n_groups, color_col, ytick_color, plot_kwargs):

from .plot_tools import get_swarm_spans

if proportional:
group_summaries_method = "proportional_error_bar"
group_summaries_offset = 0
group_summaries_line_color = err_color
else:
# Create list to gather xspans.
xspans = []
line_colors = []
for jj, c in enumerate(rawdata_axes.collections):
try:
if asymmetric_side == "right":
# currently offset is hardcoded with value of -0.2
x_max_span = -0.2
else:
if horizontal:
x_max_span = 0.1 # currently offset is hardcoded with value of 0.1
else:
_, x_max, _, _ = get_swarm_spans(c)
x_max_span = x_max - jj
xspans.append(x_max_span)
except TypeError:
# we have got a None, so skip and move on.
pass

if bootstraps_color_by_group:
line_colors.append(plot_palette_raw[all_plot_groups[jj]])

# Break the loop since hue in Seaborn adds collections to axes and it will result in index out of range
if jj >= n_groups - 1 and color_col is None:
break

if len(line_colors) != len(all_plot_groups):
line_colors = ytick_color

# hue in swarmplot would add collections to axes which will result in len(xspans) = len(all_plot_groups) + len(unique groups in hue)
if len(xspans) > len(all_plot_groups):
xspans = xspans[:len(all_plot_groups)]

group_summaries_method = "gapped_lines"
group_summaries_offset = xspans + np.array(plot_kwargs["group_summaries_offset"])
group_summaries_line_color = line_colors

return group_summaries_method, group_summaries_offset, group_summaries_line_color
10 changes: 4 additions & 6 deletions dabest/plot_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1282,7 +1282,8 @@ def slopegraph_plotter(dabest_obj, plot_data, xvar, yvar, color_col, plot_palett
horizontal : bool
If the plotting will be in horizontal format.
"""
# Jitter Kwargs
# Jitter Kwargs
# With help from devMJBL
jitter = slopegraph_kwargs["jitter"]
if jitter >= 1:
err0 = "Jitter value is too high. Defaulting to 1."
Expand Down Expand Up @@ -1313,10 +1314,7 @@ def slopegraph_plotter(dabest_obj, plot_data, xvar, yvar, color_col, plot_palett
grp_count = len(current_tuple)
# Iterate through the data for the current tuple.
for ID, observation in current_pair.iterrows():
# x_points = [t for t in range(x_start, x_start + grp_count)]
# y_points = observation[yvar].tolist()

x_points = [t + 0.15*jitter*rng.standard_t(df=6, size=None) for t in range(x_start, x_start + grp_count)]
x_points = [t + 0.15*jitter*rng.standard_t(df=6, size=None) for t in range(x_start, x_start + grp_count)] # devMJBL
y_points = observation[yvar].tolist()

if color_col is None:
Expand Down Expand Up @@ -1814,7 +1812,7 @@ def table_for_horizontal_plots(effectsize_df, ax, contrast_axes, ticks_to_plot,
table_font_size = table_kwargs['fontsize'] if table_kwargs['text_units'] == None else table_kwargs['fontsize']-2
table_text_color = table_kwargs['text_color']
text_units = '' if table_kwargs['text_units'] == None else table_kwargs['text_units']
table_gap_dashes = table_kwargs['paired_gap_dashes']
table_gap_dashes = table_kwargs['paired_gap_dashes'] # Currently unused
fontsize_label = table_kwargs['fontsize_label']
label = table_kwargs['label']

Expand Down
91 changes: 28 additions & 63 deletions dabest/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
contrast_bars=True, contrast_bars_kwargs=None,
delta_text=True, delta_text_kwargs=None,
delta_dot=True, delta_dot_kwargs=None,
horizontal=False, horizontal_table_kwargs=None,
"""
from .misc_tools import (
Expand All @@ -77,9 +76,9 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
Gardner_Altman_Plot_Aesthetic_Adjustments,
Cumming_Plot_Aesthetic_Adjustments,
Redraw_Spines,
extract_group_summaries
)
from .plot_tools import (
get_swarm_spans,
error_bar,
sankeydiag,
swarmplot,
Expand Down Expand Up @@ -114,11 +113,12 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
ytick_color = plt.rcParams["ytick.color"]

# Extract parameters and set kwargs
(dabest_obj, plot_data, xvar, yvar, is_paired, effect_size, proportional,
all_plot_groups, idx, show_delta2, show_mini_meta, float_contrast,
show_pairs, effect_size_type, group_summaries, err_color, horizontal) = get_params(
(dabest_obj, plot_data, xvar, yvar, is_paired, effect_size,
proportional, all_plot_groups, idx, show_delta2, show_mini_meta,
float_contrast, show_pairs, effect_size_type, group_summaries,
err_color, horizontal, results, es_marker_size, halfviolin_alpha, ci_type) = get_params(
effectsize_df=effectsize_df,
plot_kwargs=plot_kwargs
plot_kwargs=plot_kwargs,
)

(swarmplot_kwargs, barplot_kwargs, sankey_kwargs, violinplot_kwargs, slopegraph_kwargs,
Expand Down Expand Up @@ -279,48 +279,21 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):

# Plot the error bars.
if group_summaries is not None:
if proportional:
group_summaries_method = "proportional_error_bar"
group_summaries_offset = 0
group_summaries_line_color = err_color
else:
# Create list to gather xspans.
xspans = []
line_colors = []
for jj, c in enumerate(rawdata_axes.collections):
try:
if asymmetric_side == "right":
# currently offset is hardcoded with value of -0.2
x_max_span = -0.2
else:
if horizontal:
x_max_span = 0.1 # currently offset is hardcoded with value of 0.1
else:
_, x_max, _, _ = get_swarm_spans(c)
x_max_span = x_max - jj
xspans.append(x_max_span)
except TypeError:
# we have got a None, so skip and move on.
pass

if bootstraps_color_by_group:
line_colors.append(plot_palette_raw[all_plot_groups[jj]])

# Break the loop since hue in Seaborn adds collections to axes and it will result in index out of range
if jj >= n_groups - 1 and color_col is None:
break

if len(line_colors) != len(all_plot_groups):
line_colors = ytick_color

# hue in swarmplot would add collections to axes which will result in len(xspans) = len(all_plot_groups) + len(unique groups in hue)
if len(xspans) > len(all_plot_groups):
xspans = xspans[:len(all_plot_groups)]

group_summaries_method = "gapped_lines"
group_summaries_offset = xspans + np.array(plot_kwargs["group_summaries_offset"])
group_summaries_line_color = line_colors

(group_summaries_method,
group_summaries_offset, group_summaries_line_color) = extract_group_summaries(
proportional=proportional,
err_color=err_color,
rawdata_axes=rawdata_axes,
asymmetric_side=asymmetric_side if not proportional else None,
horizontal=horizontal,
bootstraps_color_by_group=bootstraps_color_by_group,
plot_palette_raw=plot_palette_raw,
all_plot_groups=all_plot_groups,
n_groups=n_groups,
color_col=color_col,
ytick_color=ytick_color,
plot_kwargs=plot_kwargs
)
# Plot
error_bar(
plot_data,
Expand All @@ -337,7 +310,6 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
)

# Add the counts to the rawdata axes xticks.
# if not horizontal:
add_counts_to_ticks(
plot_data=plot_data,
xvar=xvar,
Expand All @@ -347,12 +319,11 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
horizontal=horizontal,
)

# Enforce the xtick of rawdata_axes to be 0 and 1 after drawing only one sankey ----> Redundant code
# if one_sankey:
# rawdata_axes.set_xticks([0, 1])

# Plot effect sizes and bootstraps.
plot_groups = temp_all_plot_groups if (is_paired == "baseline" and show_pairs and two_col_sankey) else temp_idx if (two_col_sankey) else all_plot_groups
plot_groups = (temp_all_plot_groups if (is_paired == "baseline" and show_pairs and two_col_sankey)
else temp_idx if two_col_sankey
else all_plot_groups
)

(ticks_to_skip, ticks_to_plot,
ticks_to_skip_contrast, ticks_to_start_twocol_sankey) = extract_contrast_plotting_ticks(
Expand All @@ -365,15 +336,11 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
)

# Adjust contrast tick locations to account for different plotting styles in horizontal plots
table_axes_ticks_to_plot = ticks_to_plot
if (horizontal and proportional and not show_pairs) or (horizontal and plot_kwargs["swarm_side"] == "right"):
ticks_to_plot = [x+0.25 for x in ticks_to_plot]

# Plot the bootstraps, then the effect sizes and CIs.
es_marker_size = plot_kwargs["es_marker_size"]
halfviolin_alpha = plot_kwargs["halfviolin_alpha"]
ci_type = plot_kwargs["ci_type"]
results = effectsize_df.results

(current_group, current_control,
current_effsize, contrast_xtick_labels) = effect_size_curve_plotter(
ticks_to_plot=ticks_to_plot,
Expand Down Expand Up @@ -463,7 +430,6 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
reflines_kwargs=reflines_kwargs,
redraw_axes_kwargs=redraw_axes_kwargs,
)

else:
# For Cumming Plots only.
Cumming_Plot_Aesthetic_Adjustments(
Expand Down Expand Up @@ -494,8 +460,7 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
horizontal=horizontal
)


################################################### GRIDKEY WIP
# GRIDKEY WIP
# if gridkey_rows is None, skip everything here
gridkey_rows = plot_kwargs["gridkey_rows"]
if gridkey_rows is not None and not horizontal:
Expand Down Expand Up @@ -592,7 +557,7 @@ def effectsize_df_plotter(effectsize_df, **plot_kwargs):
effectsize_df=effectsize_df,
ax = table_axes,
contrast_axes=contrast_axes,
ticks_to_plot=ticks_to_plot,
ticks_to_plot=table_axes_ticks_to_plot,
show_mini_meta=show_mini_meta,
show_delta2=show_delta2,
table_kwargs=table_kwargs,
Expand Down
Loading

0 comments on commit eae1792

Please sign in to comment.