Create Broken Axis In Graph
I wrote the following code to make a graph: data = pd.read_excel('C:/Users/User/Desktop/Grafiek.xlsx') fig, ax = plt.subplots() ax.plot('Datum', 'Percentage', data=data) fmt_hal
Solution 1:
Borrowing heavily from the example here, we can modify it slightly to move to a broken x axis instead of y axis.
The main changes from that example to here:
- change to
sharey=True
- turn off left/right spines instead of bottom/top
- change position/angle of diagonal lines to show broken axes
- change proportion of two axes since the left axes spans a shorter range
Note for the last point, here I have made them a 1:10 ratio, because I have made the second axes span 40 months, and the first axes space 4 months. You will likely want a slightly different ratio, so will need to adjust the xlim
for each axes accordingly, and also the width_ratios
parameter.
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
drange = pd.date_range('2015-01-01', periods=78, freq='M')
data = pd.DataFrame({'Datum': drange, 'Percentage': np.random.randn(len(drange))})
fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True, gridspec_kw={'width_ratios': (1, 10)})
fig.subplots_adjust(wspace=0.05)
ax1.plot('Datum', 'Percentage', data=data)
ax2.plot('Datum', 'Percentage', data=data)
fmt_half_year1 = mdates.MonthLocator(interval=6)
fmt_half_year2 = mdates.MonthLocator(interval=6)
ax1.xaxis.set_major_locator(fmt_half_year1)
ax2.xaxis.set_major_locator(fmt_half_year2)
fmt_month1 = mdates.MonthLocator()
fmt_month2 = mdates.MonthLocator()
ax1.xaxis.set_minor_locator(fmt_month1)
ax2.xaxis.set_minor_locator(fmt_month2)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax1.format_xdata = mdates.DateFormatter('%Y-%m')
ax2.format_xdata = mdates.DateFormatter('%Y-%m')
ax1.grid(True)
ax2.grid(True)
# hide the spines between ax1 and ax2
ax1.spines.right.set_visible(False)
ax2.spines.left.set_visible(False)
ax2.yaxis.tick_right()
ax2.tick_params(labelright=False) # don't put tick labels at the top
ax1.xaxis.tick_bottom()
datemin1 = np.datetime64(data['Datum'][0], 'M')
datemax1 = np.datetime64(data['Datum'][4], 'M')
ax1.set_xlim(datemin1, datemax1)
datemin2 = np.datetime64(data['Datum'][37], 'M')
datemax2 = np.datetime64(data['Datum'][77], 'M')
ax2.set_xlim(datemin2, datemax2)
fig.text(s='Datum', x=0.5, y=0.05)
ax1.set_ylabel('Percentage')
fig.suptitle('Percentage Trained')
fig.autofmt_xdate()
d = 2.# proportion of vertical to horizontal extent of the slanted line
kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,
linestyle="none", color='k', mec='k', mew=1, clip_on=False)
ax1.plot([1, 1], [0, 1], transform=ax1.transAxes, **kwargs)
ax2.plot([0, 0], [0, 1], transform=ax2.transAxes, **kwargs)
plt.show()
Post a Comment for "Create Broken Axis In Graph"