diff --git a/rwth_nb/plots/mpl_decorations.py b/rwth_nb/plots/mpl_decorations.py index 8a548edf884629be91adfe91b473a4c444cf9a64..73ef80f62bccb8f9e2323174012c24b5678e4e3a 100644 --- a/rwth_nb/plots/mpl_decorations.py +++ b/rwth_nb/plots/mpl_decorations.py @@ -113,6 +113,86 @@ def axis(ax): ax.yaxis.label.set_fontsize(12) +def twinx(ax, visible_spine='left'): + """ + Create a twin Axes sharing the x-axis. + + Parameters + ---------- + ax: matplotlib.axes.Axes + Existing Axes + visible_spine: {'left', 'right'}, str, optional + Position of the only visible axis spine + + Returns + ------- + ax_twin: matplotlib.axes.Axes + The newly created Axes instance + + See also + -------- + matplotlib.axes.Axes.twinx + twiny: Create a twin Axes sharing the y-axis. + + """ + if visible_spine in ['left', 'right']: + # remove visible spine from hidden spine list + hidden_spines = ['top', 'bottom', 'left', 'right'] + hidden_spines.remove(visible_spine) + + # create twiny and hide spines + ax_twin = ax.twiny() + for pos in hidden_spines: + ax_twin.spines[pos].set_color('none') + + # set label position according to spine position (left/right, top) + ax_twin.yaxis.set_label_coords(visible_spine == 'right', 1) + + return ax_twin + else: + # invalid keyword + raise ValueError('Twin x-axis location must be either "left" or "right"') + + +def twiny(ax, visible_spine='top'): + """ + Create a twin Axes sharing the y-axis. + + Parameters + ---------- + ax: matplotlib.axes.Axes + Existing Axes + visible_spine: {'top', 'bottom'}, str, optional + Position of the only visible axis spine + + Returns + ------- + ax_twin: matplotlib.axes.Axes + The newly created Axes instance + + See also + -------- + matplotlib.axes.Axes.twiny + twinx: Create a twin Axes sharing the x-axis. + """ + if visible_spine in ['top', 'bottom']: + # remove visible spine from hidden spine list + hidden_spines = ['top', 'bottom', 'left', 'right'] + hidden_spines.remove(visible_spine) + + # create twiny and hide spines + ax_twin = ax.twiny() + for pos in hidden_spines: + ax_twin.spines[pos].set_color('none') + + # set label position according to spine position (right, bottom/top) + ax_twin.xaxis.set_label_coords(1, visible_spine == 'top') + + return ax_twin + else: + # invalid keyword + raise ValueError('Twin y-axis location must be either "top" or "bottom"') + def annotate_xtick(ax, txt, x, y=0, col='black', fs=12): """