Last active
July 28, 2021 18:47
-
-
Save asaboor-gh/6b997d40ad8ff5dcb0b3af66bd7681b5 to your computer and use it in GitHub Desktop.
Matplotlib Broken Axes Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def break_spines(ax,spines,symbol=u'\u2571',**kwargs): | |
"""Simulates broken axes using subplots. Need to fix heights according to given data for real aspect. Also plot the same data on each axes and set axes limits. | |
- **Parameters** | |
- ax : Axes who's spine(s) to edit. | |
- spines: str,list, str/list of any of ['top','bottom','left','right']. | |
- symbol: Defult is u'\u2571'. Its at 60 degrees. so you can apply rotation to make it any angle. | |
kwargs are passed to plt.text. | |
""" | |
kwargs.update(transform=ax.transAxes, ha='center',va = 'center') | |
_spines = [spines] if isinstance(spines,str) else spines | |
_ = [ax.spines[s].set_visible(False) for s in _spines] | |
ax.tick_params(**{sp:False for sp in _spines}) | |
if 'top' in spines: | |
ax.text(0,1,symbol,**kwargs) | |
ax.text(1,1,symbol,**kwargs) | |
if 'bottom' in spines: | |
ax.set_xticks([]) | |
ax.text(0,0,symbol,**kwargs) | |
ax.text(1,0,symbol,**kwargs) | |
if 'left' in spines: | |
ax.set_yticks([]) | |
ax.text(0,0,symbol,**kwargs) | |
ax.text(0,1,symbol,**kwargs) | |
if 'right' in spines: | |
ax.text(1,1,symbol,**kwargs) | |
ax.text(1,0,symbol,**kwargs) | |
# This code genertes figure below | |
import numpy as np | |
import matplotlib.pyplot as plt | |
x = np.linspace(0,30,50) | |
y = x**2*np.abs(np.cos(x)) | |
fig,(a1,a2) = plt.subplots(2,1,figsize=(3,2),gridspec_kw=dict(height_ratios=[4,1])) | |
a1.plot(x,y) | |
a2.plot(x,y) | |
# Set limits of data same as height_ratios to make visual correct | |
a2.set_ylim([0,100]) | |
a1.set_ylim([400,800]) | |
plt.subplots_adjust(hspace=0.2) | |
break_spines(a1,'bottom',rotation=-35) | |
break_spines(a2,['top'],rotation=-35) | |
a1.set_title('$f(x) = x^2|\cos(x)|$') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage Example