断轴

折断轴的示例,其中y轴将切割出一部分。

折断轴示例

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 30 points between [0, 0.2) originally made using np.random.rand(30)*.2
  4. pts = np.array([
  5. 0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018,
  6. 0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075,
  7. 0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008])
  8. # Now let's make two outlier points which are far away from everything.
  9. pts[[3, 14]] += .8
  10. # If we were to simply plot pts, we'd lose most of the interesting
  11. # details due to the outliers. So let's 'break' or 'cut-out' the y-axis
  12. # into two portions - use the top (ax) for the outliers, and the bottom
  13. # (ax2) for the details of the majority of our data
  14. f, (ax, ax2) = plt.subplots(2, 1, sharex=True)
  15. # plot the same data on both axes
  16. ax.plot(pts)
  17. ax2.plot(pts)
  18. # zoom-in / limit the view to different portions of the data
  19. ax.set_ylim(.78, 1.) # outliers only
  20. ax2.set_ylim(0, .22) # most of the data
  21. # hide the spines between ax and ax2
  22. ax.spines['bottom'].set_visible(False)
  23. ax2.spines['top'].set_visible(False)
  24. ax.xaxis.tick_top()
  25. ax.tick_params(labeltop=False) # don't put tick labels at the top
  26. ax2.xaxis.tick_bottom()
  27. # This looks pretty good, and was fairly painless, but you can get that
  28. # cut-out diagonal lines look with just a bit more work. The important
  29. # thing to know here is that in axes coordinates, which are always
  30. # between 0-1, spine endpoints are at these locations (0,0), (0,1),
  31. # (1,0), and (1,1). Thus, we just need to put the diagonals in the
  32. # appropriate corners of each of our axes, and so long as we use the
  33. # right transform and disable clipping.
  34. d = .015 # how big to make the diagonal lines in axes coordinates
  35. # arguments to pass to plot, just so we don't keep repeating them
  36. kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
  37. ax.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal
  38. ax.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal
  39. kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
  40. ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal
  41. ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal
  42. # What's cool about this is that now if we vary the distance between
  43. # ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),
  44. # the diagonal lines will move accordingly, and stay right at the tips
  45. # of the spines they are 'breaking'
  46. plt.show()

下载这个示例