In Matplotlib, it is possible to modify the appearance of the x-axis to indicate a discontinuity between two ranges of values.
While there is no direct way to create a discontinuous axis, you can achieve a similar effect by customizing the axis labels and appearance. One approach is to use a custom transform to create a discontinuous axis.
If you prefer not to create a custom transform, you can use subplots to achieve the desired effect. By creating two subplots with different x-axis limits and hiding the spines between them, you can simulate a discontinuous axis.
import matplotlib.pyplot as plt import numpy as np x = np.r_[0:1:0.1, 9:10:0.1] y = np.sin(x) fig, (ax, ax2) = plt.subplots(1, 2, sharey=True) ax.plot(x, y, 'bo') ax2.plot(x, y, 'bo') ax.set_xlim(0, 1) ax2.set_xlim(9, 10) ax.spines['right'].set_visible(False) ax2.spines['left'].set_visible(False) ax.yaxis.tick_left() ax2.yaxis.tick_right() plt.subplots_adjust(wspace=0.15) plt.show()
This code creates a plot with two subplots, each showing a different range of x-values. The overlap between the subplots is hidden to create the appearance of a discontinuous axis.
To add the broken axis lines (//) effect, you can use the following code:
ax.plot((1-d,1+d),(-d,+d), **kwargs) # top-left diagonal ax.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-left diagonal kwargs.update(transform=ax2.transAxes) # switch to the bottom axes ax2.plot((-d,d),(-d,+d), **kwargs) # top-right diagonal ax2.plot((-d,d),(1-d,1+d), **kwargs) # bottom-right diagonal
where d represents the size of the diagonal lines in axes coordinates. This code adds diagonal lines to the corners of each axis, giving the impression of a broken axis.
The above is the detailed content of How to Create a Discontinuous X-axis in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!