以下程序, 千万不要在 jupyter notebook 中测试, 可以使用 pycharm 测试

    1. import time
    2. import numpy as np
    3. import matplotlib.pyplot as plt
    4. def tellme(s):
    5. print(s)
    6. plt.title(s, fontsize=16)
    7. plt.draw()
    8. plt.clf()
    9. plt.setp(plt.gca(), autoscale_on=False)
    10. tellme('You will define a triangle, click to begin')
    11. plt.waitforbuttonpress()
    12. while True:
    13. pts = []
    14. while len(pts) < 3:
    15. tellme('Select 3 corners with mouse')
    16. pts = np.asarray(plt.ginput(3, timeout=-1))
    17. if len(pts) < 3:
    18. tellme('Too few points, starting over')
    19. time.sleep(1) # Wait a second
    20. ph = plt.fill(pts[:, 0], pts[:, 1], 'r', lw=2)
    21. tellme('Happy? Key click for yes, mouse click for no')
    22. if plt.waitforbuttonpress():
    23. break
    24. # Get rid of fill
    25. for p in ph:
    26. p.remove()
    27. # Define a nice function of distance from individual pts
    28. def f(x, y, pts):
    29. z = np.zeros_like(x)
    30. for p in pts:
    31. z = z + 1 / (np.sqrt((x - p[0]) ** 2 + (y - p[1]) ** 2))
    32. return 1 / z
    33. X, Y = np.meshgrid(np.linspace(-1, 1, 51), np.linspace(-1, 1, 51))
    34. Z = f(X, Y, pts)
    35. CS = plt.contour(X, Y, Z, 20)
    36. tellme('Use mouse to select contour label locations, middle button to finish')
    37. CL = plt.clabel(CS, manual=True)
    38. tellme('Now do a nested zoom, click to begin')
    39. plt.waitforbuttonpress()
    40. while True:
    41. tellme('Select two corners of zoom, middle mouse button to finish')
    42. pts = plt.ginput(2, timeout=-1)
    43. if len(pts) < 2:
    44. break
    45. (x0, y0), (x1, y1) = pts
    46. xmin, xmax = sorted([x0, x1])
    47. ymin, ymax = sorted([y0, y1])
    48. plt.xlim(xmin, xmax)
    49. plt.ylim(ymin, ymax)
    50. tellme('All Done!')
    51. plt.show()

    📃 Matplotlib交互 - 图1

    参考: