matplotlib 调整三维条形图上刻度线的位置

mbzjlibv  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(197)

下面附上的是一个代码,将创建下面的三维条形图。我遇到的问题是x轴的刻度和y轴的刻度。它们与图形上的3d条形图不匹配。我希望他们能够匹配的三维酒吧的x轴和y轴,但我有很多问题。有人能帮我吗?谢谢!我试着用“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))
mcdcgff0

mcdcgff01#

我必须说,我没有完全理解(或尝试)您的代码。但是,您的数据的xedgesxpos是从-18 et +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)

相关问题