在 python 中调整 3d 条形图上刻度线的位置

Adjusting the location of the tick marks on a 3d bar plot in python

下面附上的代码将创建下面的 3d 条形图。我遇到的问题是 x 轴刻度和 y 轴刻度。它们与图表上的 3d 条不匹配。我希望它们与 x 轴和 y 轴的 3d 条匹配,但我遇到了很多问题。有人可以帮忙吗?谢谢你!我尝试用 "ticksx" 和 "ticksy" 行调整它们的位置,但这似乎根本不起作用。

  from mpl_toolkits.mplot3d import Axes3D
  import matplotlib.pyplot as plt
  import numpy as np
  import matplotlib.cm as cm


  # To generate some test data
  column_names = ['1', '2', '3','4', '5', '6', '7','8', '9','10','11','12','13','14','15','16','17']
  row_names = ['T','S','R','P','N','M','L','K','J','H','G','F','E','D','C','B','A']

  x = np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
          1,2,3,4,5,6,7,-1,-2,-3,-4,-5,-6,-7])
  y = np.array([0,1,2,3,4,5,6,7,-1,-2,-3,-4,-5,-6,-7,
          0,0,0,0,0,0,0,0,0,0,0,0,0,0])

  XY = np.stack((x,y),axis=-1)

  def selection(XY, limitXY=[[-9,+9],[-9,+9]]):
          XY_select = []
          for elt in XY:
              if elt[0] > limitXY[0][0] and elt[0] < limitXY[0][1] and elt[1] > limitXY[1][0] and elt[1] < limitXY[1][1]:
                  XY_select.append(elt)

          return np.array(XY_select)

  XY_select = selection(XY, limitXY=[[-9,+9],[-9,+9]])


  xAmplitudes = np.array(XY_select)[:,0]#your data here
  yAmplitudes = np.array(XY_select)[:,1]#your other data here


  fig = plt.figure(figsize=(25,25)) #create a canvas, tell matplotlib it's 3d
  ax = fig.add_subplot(111, projection='3d')


  hist, xedges, yedges = np.histogram2d(x, y, bins=(17,17), range = [[-9,+9],[-9,+9]]) # you can change your bins, and the range on which to take data
  # hist is a 7X7 matrix, with the populations for each of the subspace parts.
  xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:]) -(xedges[1]-xedges[0])


  xpos = xpos.flatten()/1.
  ypos = ypos.flatten()/1.
  zpos = np.zeros_like (xpos)

  dx = (xedges [1] - xedges [0])
  dy = yedges [1] - yedges [0]
  dz = hist.flatten()   

  cmap = cm.get_cmap('jet') # Get desired colormap - you can change this!
  max_height = np.max(dz)   # get range of colorbars so we can normalize
  min_height = np.min(dz)
  # scale each z to [0,1], and get their rgb values
  rgba = [cmap((k-min_height)/max_height) for k in dz] 

  surf = ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba,alpha=0.5, zsort='max'
  ticksx = 2*np.arange(0.5, 18, 1)
  plt.xticks(ticksx, column_names,size=20)

  ticksy = 2*np.arange(0.5, 18, 1)
  plt.yticks(ticksy, row_names,size=20)
  plt.grid()
  ax.view_init(30, 40)
  plt.show()
  print('ax.azim {}'.format(ax.azim))
  print('ax.elev {}'.format(ax.elev))

我必须说我没有完全理解(或试图)您的代码。但是,您数据的 xedgesxpos 来自 -18 和 +18,但您正在创建从 1 到 36 的刻度。 通过更改行,我能够得到令人满意的结果:

ticksx = 2*np.arange(0.5, 18, 1)
plt.xticks(ticksx, column_names,size=20)

ticksy = 2*np.arange(0.5, 18, 1)
plt.yticks(ticksy, row_names,size=20)

ticksx = np.linspace(-18, 18, 17, endpoint=False)
plt.xticks(ticksx, column_names,size=20)

ticksy = np.linspace(-18, 18, 17, endpoint=False)
plt.yticks(ticksy, row_names,size=20)