matplotlib 如何绘制多个X或Y轴?

krugob8w  于 2023-11-22  发布在  其他
关注(0)|答案(2)|浏览(205)

我目前正在使用matplotlib来绘制一个测量值与2到3个其他测量值的对比图(有时是分类的)。目前,我正在将x轴上的数据分组为元组,并在绘图前对其进行排序.结果看起来像下面的左图。我想做的是用多个x轴绘制数据,如右图所示。“治疗”x的分组-轴标签将是蛋糕上的糖衣。
x1c 0d1x的数据

yqyhoc1h

yqyhoc1h1#

这在matplotlib >= 1.0.0中绝对是可能的(新的spines功能允许它)。
这需要相当多的巫毒术,虽然.我的例子远非完美,但希望它有一定的意义:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib as mpl
  4. def main():
  5. #-- Generate some data ----------------------------------------------------
  6. nx = 10
  7. x = np.linspace(0, 2*np.pi, 10)
  8. y = 2 * np.sin(x)
  9. groups = [('GroupA', (x[0], x[nx//3])),
  10. ('GroupB', (x[-2*nx//3], x[2*nx//3])),
  11. ('GroupC', (x[-nx//3], x[-1]))]
  12. #-- Plot the results ------------------------------------------------------
  13. fig = plt.figure()
  14. ax = fig.add_subplot(111)
  15. # Give ourselves a bit more room at the bottom
  16. plt.subplots_adjust(bottom=0.2)
  17. ax.plot(x,y, 'k^')
  18. # Drop the bottom spine by 40 pts
  19. ax.spines['bottom'].set_position(('outward', 40))
  20. # Make a second bottom spine in the position of the original bottom spine
  21. make_second_bottom_spine(label='Treatment')
  22. # Annotate the groups
  23. for name, xspan in groups:
  24. annotate_group(name, xspan)
  25. plt.xlabel('Dose')
  26. plt.ylabel('Response')
  27. plt.title('Experimental Data')
  28. plt.show()
  29. def annotate_group(name, xspan, ax=None):
  30. """Annotates a span of the x-axis"""
  31. def annotate(ax, name, left, right, y, pad):
  32. arrow = ax.annotate(name,
  33. xy=(left, y), xycoords='data',
  34. xytext=(right, y-pad), textcoords='data',
  35. annotation_clip=False, verticalalignment='top',
  36. horizontalalignment='center', linespacing=2.0,
  37. arrowprops=dict(arrowstyle='-', shrinkA=0, shrinkB=0,
  38. connectionstyle='angle,angleB=90,angleA=0,rad=5')
  39. )
  40. return arrow
  41. if ax is None:
  42. ax = plt.gca()
  43. ymin = ax.get_ylim()[0]
  44. ypad = 0.01 * np.ptp(ax.get_ylim())
  45. xcenter = np.mean(xspan)
  46. left_arrow = annotate(ax, name, xspan[0], xcenter, ymin, ypad)
  47. right_arrow = annotate(ax, name, xspan[1], xcenter, ymin, ypad)
  48. return left_arrow, right_arrow
  49. def make_second_bottom_spine(ax=None, label=None, offset=0, labeloffset=20):
  50. """Makes a second bottom spine"""
  51. if ax is None:
  52. ax = plt.gca()
  53. second_bottom = mpl.spines.Spine(ax, 'bottom', ax.spines['bottom']._path)
  54. second_bottom.set_position(('outward', offset))
  55. ax.spines['second_bottom'] = second_bottom
  56. if label is not None:
  57. # Make a new xlabel
  58. ax.annotate(label,
  59. xy=(0.5, 0), xycoords='axes fraction',
  60. xytext=(0, -labeloffset), textcoords='offset points',
  61. verticalalignment='top', horizontalalignment='center')
  62. if __name__ == '__main__':
  63. main()

字符串


的数据

展开查看全部
zwghvu4y

zwghvu4y2#

乔的例子很好。我也会把我的也加进去。它从here那里偷来的。

  1. import matplotlib.pyplot as plt
  2. import matplotlib.ticker as ticker
  3. ## the following two functions override the default behavior or twiny()
  4. def make_patch_spines_invisible(ax):
  5. ax.set_frame_on(True)
  6. ax.patch.set_visible(False)
  7. for sp in ax.spines.itervalues():
  8. sp.set_visible(False)
  9. def make_spine_invisible(ax, direction):
  10. if direction in ["right", "left"]:
  11. ax.yaxis.set_ticks_position(direction)
  12. ax.yaxis.set_label_position(direction)
  13. elif direction in ["top", "bottom"]:
  14. ax.xaxis.set_ticks_position(direction)
  15. ax.xaxis.set_label_position(direction)
  16. else:
  17. raise ValueError("Unknown Direction : %s" % (direction,))
  18. ax.spines[direction].set_visible(True)
  19. data = (('A',0.01),('A',0.02),('B',0.10),('B',0.20)) # fake data
  20. fig = plt.figure(1)
  21. sb = fig.add_subplot(111)
  22. sb.xaxis.set_major_locator(ticker.FixedLocator([0,1,2,3]))
  23. sb.plot([i[1] for i in data],"*",markersize=10)
  24. sb.set_xlabel("dose")
  25. plt.subplots_adjust(bottom=0.17) # make room on bottom
  26. par2 = sb.twiny() # create a second axes
  27. par2.spines["bottom"].set_position(("axes", -.1)) # move it down
  28. ## override the default behavior for a twiny axis
  29. make_patch_spines_invisible(par2)
  30. make_spine_invisible(par2, "bottom")
  31. par2.set_xlabel("treatment")
  32. par2.plot([i[1] for i in data],"*",markersize=10) #redraw to put twiny on same scale
  33. par2.xaxis.set_major_locator(ticker.FixedLocator([0,1,2,3]))
  34. par2.xaxis.set_ticklabels([i[0] for i in data])
  35. plt.show()

字符串
制作:


的数据

展开查看全部

相关问题