This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
I was looking gfor a way to show the numerical value of the median for a box plot and found the code block for matplotlib/seaborn below. Unfortunatly I do not undertsand how it works. Does anyone understand matplotlib enough to walk me through how this code works so that I can adapt the solution to later problems? ~~~ import seaborn as sns import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects
def addmedian_labels(ax, precision='.1f'): lines = ax.get_lines() boxes = [c for c in ax.get_children() if type(c).name_ == 'PathPatch'] lines_per_box = int(len(lines) / len(boxes)) for median in lines[4:len(lines):lines_per_box]: x, y = (data.mean() for data in median.get_data()) # choose value depending on horizontal or vertical plot orientation value = x if (median.get_xdata()[1] - median.get_xdata()[0]) == 0 else y text = ax.text(x, y, f'{value:{precision}}', ha='center', va='center', fontweight='bold', color='white') # create median-colored border around white text for contrast text.set_path_effects([ path_effects.Stroke(linewidth=3, foreground=median.get_color()), path_effects.Normal(), ])
sns.set_style("darkgrid") tips = sns.load_dataset("tips") fig, axes = plt.subplots(2, 2, figsize=(10, 10)) for i_fly, show_fliers in enumerate([True, False]): for i_data, data_kwargs in enumerate([{'x': 'day', 'y': 'total_bill'}, {'y': 'day', 'x': 'total_bill'}]): box_plot = sns.boxplot(ax=axes[i_fly, i_data], **data_kwargs, data=tips, showfliers=show_fliers, hue="sex") add_median_labels(box_plot.axes) box_plot.axes.set_title(( f"{['Fliers', 'No fliers'][i_fly]}, " f"{['vertical', 'horizontal'][i_data]}")) plt.show() ~~~
Subreddit
Post Details
- Posted
- 3 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnpython...