散点图视图拆解

从散点图创建直方图,并将其添加到散点图的两侧。

散点图视图拆解示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.ticker import NullFormatter
  4. # Fixing random state for reproducibility
  5. np.random.seed(19680801)
  6. # the random data
  7. x = np.random.randn(1000)
  8. y = np.random.randn(1000)
  9. nullfmt = NullFormatter() # no labels
  10. # definitions for the axes
  11. left, width = 0.1, 0.65
  12. bottom, height = 0.1, 0.65
  13. bottom_h = left_h = left + width + 0.02
  14. rect_scatter = [left, bottom, width, height]
  15. rect_histx = [left, bottom_h, width, 0.2]
  16. rect_histy = [left_h, bottom, 0.2, height]
  17. # start with a rectangular Figure
  18. plt.figure(1, figsize=(8, 8))
  19. axScatter = plt.axes(rect_scatter)
  20. axHistx = plt.axes(rect_histx)
  21. axHisty = plt.axes(rect_histy)
  22. # no labels
  23. axHistx.xaxis.set_major_formatter(nullfmt)
  24. axHisty.yaxis.set_major_formatter(nullfmt)
  25. # the scatter plot:
  26. axScatter.scatter(x, y)
  27. # now determine nice limits by hand:
  28. binwidth = 0.25
  29. xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
  30. lim = (int(xymax/binwidth) + 1) * binwidth
  31. axScatter.set_xlim((-lim, lim))
  32. axScatter.set_ylim((-lim, lim))
  33. bins = np.arange(-lim, lim + binwidth, binwidth)
  34. axHistx.hist(x, bins=bins)
  35. axHisty.hist(y, bins=bins, orientation='horizontal')
  36. axHistx.set_xlim(axScatter.get_xlim())
  37. axHisty.set_ylim(axScatter.get_ylim())
  38. plt.show()

下载这个示例