脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python绘图Matplotlib之坐标轴及刻度总结

Python绘图Matplotlib之坐标轴及刻度总结

2021-07-26 00:14wuzlun Python

这篇文章主要介绍了Python绘图Matplotlib之坐标轴及刻度总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

学习https://matplotlib.org/gallery/index.html 记录,描述不一定准确,具体请参考官网

Matplotlib使用总结图

Python绘图Matplotlib之坐标轴及刻度总结

  1. import matplotlib.pyplot as plt
  2. plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
  3. plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
  4.  
  5. import pandas as pd
  6. import numpy as np

新建隐藏坐标轴

  1. from mpl_toolkits.axisartist.axislines import SubplotZero
  2. import numpy as np
  3.  
  4. fig = plt.figure(1, (10, 6))
  5.  
  6. ax = SubplotZero(fig, 1, 1, 1)
  7. fig.add_subplot(ax)
  8.  
  9. """新建坐标轴"""
  10. ax.axis["xzero"].set_visible(True)
  11. ax.axis["xzero"].label.set_text("新建y=0坐标")
  12. ax.axis["xzero"].label.set_color('green')
  13. # ax.axis['yzero'].set_visible(True)
  14. # ax.axis["yzero"].label.set_text("新建x=0坐标")
  15.  
  16. # 新建一条y=2横坐标轴
  17. ax.axis["新建1"] = ax.new_floating_axis(nth_coord=0, value=2,axis_direction="bottom")
  18. ax.axis["新建1"].toggle(all=True)
  19. ax.axis["新建1"].label.set_text("y = 2横坐标")
  20. ax.axis["新建1"].label.set_color('blue')
  21.  
  22. """坐标箭头"""
  23. ax.axis["xzero"].set_axisline_style("-|>")
  24.  
  25. """隐藏坐标轴"""
  26. # 方法一:隐藏上边及右边
  27. # ax.axis["right"].set_visible(False)
  28. # ax.axis["top"].set_visible(False)
  29. #方法二:可以一起写
  30. ax.axis["top",'right'].set_visible(False)
  31. # 方法三:利用 for in
  32. # for n in ["bottom", "top", "right"]:
  33. # ax.axis[n].set_visible(False)
  34.  
  35. """设置刻度"""
  36. ax.set_ylim(-3, 3)
  37. ax.set_yticks([-1,-0.5,0,0.5,1])
  38. ax.set_xlim([-5, 8])
  39. # ax.set_xticks([-5,5,1])
  40.  
  41. #设置网格样式
  42. ax.grid(True, linestyle='-.')
  43.  
  44. xx = np.arange(-4, 2*np.pi, 0.01)
  45. ax.plot(xx, np.sin(xx))
  46.  
  47. # 于 offset 处新建一条纵坐标
  48. offset = (40, 0)
  49. new_axisline = ax.get_grid_helper().new_fixed_axis
  50. ax.axis["新建2"] = new_axisline(loc="right", offset=offset, axes=ax)
  51. ax.axis["新建2"].label.set_text("新建纵坐标")
  52. ax.axis["新建2"].label.set_color('red')
  53.  
  54. plt.show()
  55. # 存为图像
  56. # fig.savefig('test.png')

Python绘图Matplotlib之坐标轴及刻度总结

  1. from mpl_toolkits.axes_grid1 import host_subplot
  2. import mpl_toolkits.axisartist as AA
  3. import matplotlib.pyplot as plt
  4.  
  5. host = host_subplot(111, axes_class=AA.Axes)
  6. plt.subplots_adjust(right=0.75)
  7.  
  8. par1 = host.twinx()
  9. par2 = host.twinx()
  10.  
  11. offset = 100
  12. new_fixed_axis = par2.get_grid_helper().new_fixed_axis
  13. par2.axis["right"] = new_fixed_axis(loc="right",
  14. axes=par2,
  15. offset=(offset, 0))
  16.  
  17. par1.axis["right"].toggle(all=True)
  18. par2.axis["right"].toggle(all=True)
  19.  
  20. host.set_xlim(0, 2)
  21. host.set_ylim(0, 2)
  22.  
  23. host.set_xlabel("Distance")
  24. host.set_ylabel("Density")
  25. par1.set_ylabel("Temperature")
  26. par2.set_ylabel("Velocity")
  27.  
  28. p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
  29. p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
  30. p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
  31.  
  32. par1.set_ylim(0, 4)
  33. par2.set_ylim(1, 65)
  34.  
  35. host.legend()
  36.  
  37. host.axis["left"].label.set_color(p1.get_color())
  38. par1.axis["right"].label.set_color(p2.get_color())
  39. par2.axis["right"].label.set_color(p3.get_color())
  40.  
  41. plt.draw()
  42. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

  1. # 第二坐标
  2. fig, ax_f = plt.subplots()
  3. # 这步是关键
  4. ax_c = ax_f.twinx()
  5. ax_d = ax_f.twiny()
  6.  
  7. # automatically update ylim of ax2 when ylim of ax1 changes.
  8. # ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)
  9. ax_f.plot(np.linspace(-40, 120, 100))
  10. ax_f.set_xlim(0, 100)
  11.  
  12. # ax_f.set_title('第二坐标', size=14)
  13. ax_f.set_ylabel('Y轴',color='r')
  14. ax_f.set_xlabel('X轴',color='c')
  15.  
  16. ax_c.set_ylabel('第二Y轴', color='b')
  17. ax_c.set_yticklabels(["$0$", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
  18. # ax_c.set_ylim(1,5)
  19.  
  20. ax_d.set_xlabel('第二X轴', color='g')
  21. ax_d.set_xlim(-1,1)
  22.  
  23. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

刻度及标记

  1. import mpl_toolkits.axisartist.axislines as axislines
  2.  
  3. fig = plt.figure(1, figsize=(10, 6))
  4. fig.subplots_adjust(bottom=0.2)
  5.  
  6. # 子图1
  7. ax1 = axislines.Subplot(fig, 131)
  8. fig.add_subplot(ax1)
  9. # for axis in ax.axis.values():
  10. # axis.major_ticks.set_tick_out(True) # 标签全部在外部
  11. ax1.axis[:].major_ticks.set_tick_out(True) # 这句和上面的for循环功能相同
  12. ax1.axis["left"].label.set_text("子图1 left标签") # 显示在左边
  13. # 设置刻度
  14. ax1.set_yticks([2,4,6,8])
  15. ax1.set_xticks([0.2,0.4,0.6,0.8])
  16.  
  17. # 子图2
  18. ax2 = axislines.Subplot(fig, 132)
  19. fig.add_subplot(ax2)
  20. ax2.set_yticks([1,3,5,7])
  21. ax2.set_yticklabels(('one','two','three', 'four', 'five')) # 不显示‘five'
  22. ax2.set_xlim(5, 0) # X轴刻度
  23. ax2.axis["left"].set_axis_direction("right")
  24. ax2.axis["left"].label.set_text("子图2 left标签") # 显示在右边
  25. ax2.axis["bottom"].set_axis_direction("top")
  26. ax2.axis["right"].set_axis_direction("left")
  27. ax2.axis["top"].set_axis_direction("bottom")
  28.  
  29. # 子图3
  30. ax3 = axislines.Subplot(fig, 133)
  31. fig.add_subplot(ax3)
  32. # 前两位表示X轴范围,后两位表示Y轴范围
  33. ax3.axis([40, 160, 0, 0.03])
  34. ax3.axis["left"].set_axis_direction("right")
  35. ax3.axis[:].major_ticks.set_tick_out(True)
  36.  
  37. ax3.axis["left"].label.set_text("Long Label Left")
  38. ax3.axis["bottom"].label.set_text("Label Bottom")
  39. ax3.axis["right"].label.set_text("Long Label Right")
  40. ax3.axis["right"].label.set_visible(True)
  41. ax3.axis["left"].label.set_pad(0)
  42. ax3.axis["bottom"].label.set_pad(20)
  43.  
  44. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

  1. import matplotlib.ticker as ticker
  2.  
  3. # Fixing random state for reproducibility
  4. np.random.seed(19680801)
  5.  
  6. fig, ax = plt.subplots()
  7. ax.plot(100*np.random.rand(20))
  8.  
  9. # 设置 y坐标轴刻度
  10. formatter = ticker.FormatStrFormatter('$%1.2f')
  11. ax.yaxis.set_major_formatter(formatter)
  12.  
  13. # 刻度
  14. for tick in ax.yaxis.get_major_ticks():
  15. tick.label1On = True # label1On 左边纵坐标
  16. tick.label2On = True # label2On 右边纵坐标
  17. tick.label1.set_color('red')
  18. tick.label2.set_color('green')
  19.  
  20. # 刻度线
  21. for line in ax.yaxis.get_ticklines():
  22. # line is a Line2D instance
  23. line.set_color('green')
  24. line.set_markersize(25)
  25. line.set_markeredgewidth(3)
  26.  
  27. # 刻度 文字
  28. for label in ax.xaxis.get_ticklabels():
  29. # label is a Text instance
  30. label.set_color('red')
  31. label.set_rotation(45)
  32. label.set_fontsize(16)
  33.  
  34. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

  1. import mpl_toolkits.axisartist as axisartist
  2. def setup_axes(fig, rect):
  3. ax = axisartist.Subplot(fig, rect)
  4. fig.add_subplot(ax)
  5.  
  6. ax.set_yticks([0.2, 0.8])
  7. # 设置刻度标记
  8. ax.set_yticklabels(["short", "loooong"])
  9. ax.set_xticks([0.2, 0.8])
  10. ax.set_xticklabels([r"$\frac{1}{2}\pi$", r"$\pi$"])
  11.  
  12. return ax
  13.  
  14. fig = plt.figure(1, figsize=(3, 5))
  15. fig.subplots_adjust(left=0.5, hspace=0.7)
  16.  
  17. ax = setup_axes(fig, 311)
  18. ax.set_ylabel("ha=right")
  19. ax.set_xlabel("va=baseline")
  20.  
  21. ax = setup_axes(fig, 312)
  22. # 刻度标签对齐方式
  23. ax.axis["left"].major_ticklabels.set_ha("center") # 居中
  24. ax.axis["bottom"].major_ticklabels.set_va("top") # 项部
  25. ax.set_ylabel("ha=center")
  26. ax.set_xlabel("va=top")
  27.  
  28. ax = setup_axes(fig, 313)
  29. ax.axis["left"].major_ticklabels.set_ha("left") # 左边
  30. ax.axis["bottom"].major_ticklabels.set_va("bottom") # 底部
  31. ax.set_ylabel("ha=left")
  32. ax.set_xlabel("va=bottom")
  33.  
  34. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

共享坐标轴

  1. # 共享坐标轴 方法一
  2. t = np.arange(0.01, 5.0, 0.01)
  3. s1 = np.sin(2 * np.pi * t)
  4. s2 = np.exp(-t)
  5. s3 = np.sin(4 * np.pi * t)
  6.  
  7. plt.subplots_adjust(top=2) #位置调整
  8.  
  9. ax1 = plt.subplot(311)
  10. plt.plot(t, s1)
  11. plt.setp(ax1.get_xticklabels(), fontsize=6)
  12. plt.title('我是原坐标')
  13.  
  14. # 只共享X轴 sharex
  15. ax2 = plt.subplot(312, sharex=ax1)
  16. plt.plot(t, s2)
  17. # make these tick labels invisible
  18. plt.setp(ax2.get_xticklabels(), visible=False)
  19. plt.title('我共享了X轴')
  20.  
  21. # 共享X轴和Y轴 sharex、sharey
  22. ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
  23. plt.plot(t, s3)
  24. plt.xlim(0.01, 5.0) #不起作用
  25. plt.title('我共享了X轴和Y轴')
  26. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

  1. # 共享坐标轴 方法二
  2. x = np.linspace(0, 2 * np.pi, 400)
  3. y = np.sin(x ** 2)
  4.  
  5. f, axarr = plt.subplots(2, sharex=True)
  6. f.suptitle('共享X轴')
  7. axarr[0].plot(x, y)
  8. axarr[1].scatter(x, y, color='r')
  9.  
  10. f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
  11. f.suptitle('共享Y轴')
  12. ax1.plot(x, y)
  13. ax2.scatter(x, y)
  14.  
  15. f, axarr = plt.subplots(3, sharex=True, sharey=True)
  16. f.suptitle('同时共享X轴和Y轴')
  17. axarr[0].plot(x, y)
  18. axarr[1].scatter(x, y)
  19. axarr[2].scatter(x, 2 * y ** 2 - 1, color='g')
  20. # 间距调整为0
  21. f.subplots_adjust(hspace=0)
  22. # 设置全部标签在外部
  23. for ax in axarr:
  24. ax.label_outer()

Python绘图Matplotlib之坐标轴及刻度总结

Python绘图Matplotlib之坐标轴及刻度总结

Python绘图Matplotlib之坐标轴及刻度总结

放大缩小

  1. def f(t):
  2. return np.exp(-t) * np.cos(2*np.pi*t)
  3.  
  4. t1 = np.arange(0.0, 3.0, 0.01)
  5.  
  6. ax1 = plt.subplot(212)
  7. ax1.margins(0.05) # Default margin is 0.05, value 0 means fit
  8. ax1.plot(t1, f(t1), 'k')
  9.  
  10. ax2 = plt.subplot(221)
  11. ax2.margins(2, 2) # Values >0.0 zoom out
  12. ax2.plot(t1, f(t1), 'r')
  13. ax2.set_title('Zoomed out')
  14.  
  15. ax3 = plt.subplot(222)
  16. ax3.margins(x=0, y=-0.25) # Values in (-0.5, 0.0) zooms in to center
  17. ax3.plot(t1, f(t1), 'g')
  18. ax3.set_title('Zoomed in')
  19.  
  20. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

  1. from matplotlib.transforms import Bbox, TransformedBbox, \
  2. blended_transform_factory
  3.  
  4. from mpl_toolkits.axes_grid1.inset_locator import BboxPatch, BboxConnector,\
  5. BboxConnectorPatch
  6.  
  7. def connect_bbox(bbox1, bbox2,
  8. loc1a, loc2a, loc1b, loc2b,
  9. prop_lines, prop_patches=None):
  10. if prop_patches is None:
  11. prop_patches = prop_lines.copy()
  12. prop_patches["alpha"] = prop_patches.get("alpha", 1) * 0.2
  13.  
  14. c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines)
  15. c1.set_clip_on(False)
  16. c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines)
  17. c2.set_clip_on(False)
  18.  
  19. bbox_patch1 = BboxPatch(bbox1, **prop_patches)
  20. bbox_patch2 = BboxPatch(bbox2, **prop_patches)
  21.  
  22. p = BboxConnectorPatch(bbox1, bbox2,
  23. # loc1a=3, loc2a=2, loc1b=4, loc2b=1,
  24. loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,
  25. **prop_patches)
  26. p.set_clip_on(False)
  27.  
  28. return c1, c2, bbox_patch1, bbox_patch2, p
  29.  
  30. def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):
  31. """
  32. ax1 : the main axes
  33. ax1 : the zoomed axes
  34. (xmin,xmax) : the limits of the colored area in both plot axes.
  35.  
  36. connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will
  37. be marked. The keywords parameters will be used ti create
  38. patches.
  39.  
  40. """
  41.  
  42. trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
  43. trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)
  44.  
  45. bbox = Bbox.from_extents(xmin, 0, xmax, 1)
  46.  
  47. mybbox1 = TransformedBbox(bbox, trans1)
  48. mybbox2 = TransformedBbox(bbox, trans2)
  49.  
  50. prop_patches = kwargs.copy()
  51. prop_patches["ec"] = "none"
  52. prop_patches["alpha"] = 0.2
  53.  
  54. c1, c2, bbox_patch1, bbox_patch2, p = \
  55. connect_bbox(mybbox1, mybbox2,
  56. loc1a=3, loc2a=2, loc1b=4, loc2b=1,
  57. prop_lines=kwargs, prop_patches=prop_patches)
  58.  
  59. ax1.add_patch(bbox_patch1)
  60. ax2.add_patch(bbox_patch2)
  61. ax2.add_patch(c1)
  62. ax2.add_patch(c2)
  63. ax2.add_patch(p)
  64.  
  65. return c1, c2, bbox_patch1, bbox_patch2, p
  66.  
  67. def zoom_effect02(ax1, ax2, **kwargs):
  68. """
  69. ax1 : the main axes
  70. ax1 : the zoomed axes
  71.  
  72. Similar to zoom_effect01. The xmin & xmax will be taken from the
  73. ax1.viewLim.
  74. """
  75.  
  76. tt = ax1.transScale + (ax1.transLimits + ax2.transAxes)
  77. trans = blended_transform_factory(ax2.transData, tt)
  78.  
  79. mybbox1 = ax1.bbox
  80. mybbox2 = TransformedBbox(ax1.viewLim, trans)
  81.  
  82. prop_patches = kwargs.copy()
  83. prop_patches["ec"] = "none"
  84. prop_patches["alpha"] = 0.2
  85.  
  86. c1, c2, bbox_patch1, bbox_patch2, p = \
  87. connect_bbox(mybbox1, mybbox2,
  88. loc1a=3, loc2a=2, loc1b=4, loc2b=1,
  89. prop_lines=kwargs, prop_patches=prop_patches)
  90.  
  91. ax1.add_patch(bbox_patch1)
  92. ax2.add_patch(bbox_patch2)
  93. ax2.add_patch(c1)
  94. ax2.add_patch(c2)
  95. ax2.add_patch(p)
  96.  
  97. return c1, c2, bbox_patch1, bbox_patch2, p
  98.  
  99. import matplotlib.pyplot as plt
  100.  
  101. plt.figure(1, figsize=(5, 5))
  102. ax1 = plt.subplot(221)
  103. ax2 = plt.subplot(212)
  104. ax2.set_xlim(0, 1)
  105. ax2.set_xlim(0, 5)
  106. zoom_effect01(ax1, ax2, 0.2, 0.8)
  107.  
  108. ax1 = plt.subplot(222)
  109. ax1.set_xlim(2, 3)
  110. ax2.set_xlim(0, 5)
  111. zoom_effect02(ax1, ax2)
  112.  
  113. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

嵌入式标轴轴

  1. # 相同随机数
  2. np.random.seed(19680801)
  3.  
  4. # create some data to use for the plot
  5. dt = 0.001
  6. t = np.arange(0.0, 10.0, dt)
  7. r = np.exp(-t[:1000] / 0.05) # impulse response
  8. x = np.random.randn(len(t))
  9. s = np.convolve(x, r)[:len(x)] * dt # colored noise
  10.  
  11. # the main axes is subplot(111) by default
  12. plt.plot(t, s)
  13. #坐标轴
  14. plt.axis([0, 1, 1.1 * np.min(s), 2 * np.max(s)])
  15. plt.xlabel('time (s)')
  16. plt.ylabel('current (nA)')
  17. plt.title('Gaussian colored noise')
  18.  
  19. # this is an inset axes over the main axes
  20. a = plt.axes([.65, .6, .2, .2], facecolor='k')
  21. n, bins, patches = plt.hist(s, 400, density=True, orientation='horizontal')
  22. plt.title('Probability')
  23. plt.xticks([])
  24. plt.yticks([])
  25.  
  26. # # this is another inset axes over the main axes
  27. a = plt.axes([0.2, 0.6, .2, .2], facecolor='k')
  28. plt.plot(t[:len(r)], r)
  29. plt.title('Impulse response')
  30. plt.xlim(0, 0.2)
  31. plt.xticks([])
  32. plt.yticks([])
  33.  
  34. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

非常规坐标轴

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

Python绘图Matplotlib之坐标轴及刻度总结

  1. from matplotlib.transforms import Affine2D
  2. import mpl_toolkits.axisartist.floating_axes as floating_axes
  3. import numpy as np
  4. import mpl_toolkits.axisartist.angle_helper as angle_helper
  5. from matplotlib.projections import PolarAxes
  6. from mpl_toolkits.axisartist.grid_finder import (FixedLocator, MaxNLocator,
  7. DictFormatter)
  8. import matplotlib.pyplot as plt
  9.  
  10. # Fixing random state for reproducibility
  11. np.random.seed(19680801)
  12.  
  13. def setup_axes1(fig, rect):
  14. """
  15. A simple one.
  16. """
  17. tr = Affine2D().scale(2, 1).rotate_deg(30)
  18.  
  19. grid_helper = floating_axes.GridHelperCurveLinear(
  20. tr, extremes=(-0.5, 3.5, 0, 4))
  21.  
  22. ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
  23. fig.add_subplot(ax1)
  24.  
  25. aux_ax = ax1.get_aux_axes(tr)
  26.  
  27. grid_helper.grid_finder.grid_locator1._nbins = 4
  28. grid_helper.grid_finder.grid_locator2._nbins = 4
  29.  
  30. return ax1, aux_ax
  31.  
  32. def setup_axes2(fig, rect):
  33. """
  34. With custom locator and formatter.
  35. Note that the extreme values are swapped.
  36. """
  37. tr = PolarAxes.PolarTransform()
  38.  
  39. pi = np.pi
  40. angle_ticks = [(0, r"$0$"),
  41. (.25*pi, r"$\frac{1}{4}\pi$"),
  42. (.5*pi, r"$\frac{1}{2}\pi$")]
  43. grid_locator1 = FixedLocator([v for v, s in angle_ticks])
  44. tick_formatter1 = DictFormatter(dict(angle_ticks))
  45.  
  46. grid_locator2 = MaxNLocator(2)
  47.  
  48. grid_helper = floating_axes.GridHelperCurveLinear(
  49. tr, extremes=(.5*pi, 0, 2, 1),
  50. grid_locator1=grid_locator1,
  51. grid_locator2=grid_locator2,
  52. tick_formatter1=tick_formatter1,
  53. tick_formatter2=None)
  54.  
  55. ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
  56. fig.add_subplot(ax1)
  57.  
  58. # create a parasite axes whose transData in RA, cz
  59. aux_ax = ax1.get_aux_axes(tr)
  60.  
  61. aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
  62. ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
  63. # drawn twice, and possibly over some other
  64. # artists. So, we decrease the zorder a bit to
  65. # prevent this.
  66.  
  67. return ax1, aux_ax
  68.  
  69. def setup_axes3(fig, rect):
  70. """
  71. Sometimes, things like axis_direction need to be adjusted.
  72. """
  73.  
  74. # rotate a bit for better orientation
  75. tr_rotate = Affine2D().translate(-95, 0)
  76.  
  77. # scale degree to radians
  78. tr_scale = Affine2D().scale(np.pi/180., 1.)
  79.  
  80. tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()
  81.  
  82. grid_locator1 = angle_helper.LocatorHMS(4)
  83. tick_formatter1 = angle_helper.FormatterHMS()
  84.  
  85. grid_locator2 = MaxNLocator(3)
  86.  
  87. # Specify theta limits in degrees
  88. ra0, ra1 = 8.*15, 14.*15
  89. # Specify radial limits
  90. cz0, cz1 = 0, 14000
  91. grid_helper = floating_axes.GridHelperCurveLinear(
  92. tr, extremes=(ra0, ra1, cz0, cz1),
  93. grid_locator1=grid_locator1,
  94. grid_locator2=grid_locator2,
  95. tick_formatter1=tick_formatter1,
  96. tick_formatter2=None)
  97.  
  98. ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
  99. fig.add_subplot(ax1)
  100.  
  101. # adjust axis
  102. ax1.axis["left"].set_axis_direction("bottom")
  103. ax1.axis["right"].set_axis_direction("top")
  104.  
  105. ax1.axis["bottom"].set_visible(False)
  106. ax1.axis["top"].set_axis_direction("bottom")
  107. ax1.axis["top"].toggle(ticklabels=True, label=True)
  108. ax1.axis["top"].major_ticklabels.set_axis_direction("top")
  109. ax1.axis["top"].label.set_axis_direction("top")
  110.  
  111. ax1.axis["left"].label.set_text(r"cz [km$^{-1}$]")
  112. ax1.axis["top"].label.set_text(r"$\alpha_{1950}$")
  113.  
  114. # create a parasite axes whose transData in RA, cz
  115. aux_ax = ax1.get_aux_axes(tr)
  116.  
  117. aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
  118. ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
  119. # drawn twice, and possibly over some other
  120. # artists. So, we decrease the zorder a bit to
  121. # prevent this.
  122.  
  123. return ax1, aux_ax
  124.  
  125. fig = plt.figure(1, figsize=(8, 4))
  126. fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95)
  127.  
  128. ax1, aux_ax1 = setup_axes1(fig, 131)
  129. aux_ax1.bar([0, 1, 2, 3], [3, 2, 1, 3])
  130.  
  131. ax2, aux_ax2 = setup_axes2(fig, 132)
  132. theta = np.random.rand(10)*.5*np.pi
  133. radius = np.random.rand(10) + 1.
  134. aux_ax2.scatter(theta, radius)
  135.  
  136. ax3, aux_ax3 = setup_axes3(fig, 133)
  137.  
  138. theta = (8 + np.random.rand(10)*(14 - 8))*15. # in degrees
  139. radius = np.random.rand(10)*14000.
  140. aux_ax3.scatter(theta, radius)
  141.  
  142. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import mpl_toolkits.axisartist.angle_helper as angle_helper
  4. from matplotlib.projections import PolarAxes
  5. from matplotlib.transforms import Affine2D
  6. from mpl_toolkits.axisartist import SubplotHost
  7. from mpl_toolkits.axisartist import GridHelperCurveLinear
  8.  
  9. def curvelinear_test2(fig):
  10. """Polar projection, but in a rectangular box.
  11. """
  12. # see demo_curvelinear_grid.py for details
  13. tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()
  14.  
  15. extreme_finder = angle_helper.ExtremeFinderCycle(20,
  16. 20,
  17. lon_cycle=360,
  18. lat_cycle=None,
  19. lon_minmax=None,
  20. lat_minmax=(0,
  21. np.inf),
  22. )
  23.  
  24. grid_locator1 = angle_helper.LocatorDMS(12)
  25.  
  26. tick_formatter1 = angle_helper.FormatterDMS()
  27.  
  28. grid_helper = GridHelperCurveLinear(tr,
  29. extreme_finder=extreme_finder,
  30. grid_locator1=grid_locator1,
  31. tick_formatter1=tick_formatter1
  32. )
  33.  
  34. ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
  35.  
  36. fig.add_subplot(ax1)
  37.  
  38. # Now creates floating axis
  39.  
  40. # floating axis whose first coordinate (theta) is fixed at 60
  41. ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
  42. axis.label.set_text(r"$\theta = 60^{\circ}$")
  43. axis.label.set_visible(True)
  44.  
  45. # floating axis whose second coordinate (r) is fixed at 6
  46. ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
  47. axis.label.set_text(r"$r = 6$")
  48.  
  49. ax1.set_aspect(1.)
  50. ax1.set_xlim(-5, 12)
  51. ax1.set_ylim(-5, 10)
  52.  
  53. ax1.grid(True)
  54.  
  55. fig = plt.figure(1, figsize=(5, 5))
  56. fig.clf()
  57.  
  58. curvelinear_test2(fig)
  59.  
  60. plt.show()

Python绘图Matplotlib之坐标轴及刻度总结

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/wuzlun/article/details/80053277

延伸 · 阅读

精彩推荐