这是一些显示3D直方图的代码。但是,右下角的跟踪器无法正确显示鼠标的位置。
当鼠标明显超过x = e
时,跟踪器会显示c
。跟踪器说z = 01-02
。那是怎么回事? (z跟踪器值似乎由y轴格式化程序控制。)
如何修复代码?
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.axes3d as axes3d
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import datetime as dt
import random
np.random.seed(0)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection = '3d')
cmap = plt.get_cmap('RdBu')
event_labels = 'abcdefghij'
events = range(len(event_labels))
label_map = dict(zip(events,event_labels))
dates = mdates.drange(dt.datetime(2012, 10, 1),
dt.datetime(2012, 10, 10),
dt.timedelta(days = 1))
events_list = [(random.choice(dates), random.choice(events))
for i in range(50)]
event_array, date_array = zip(*events_list)
# Much of the code below comes from
# http://matplotlib.org/examples/mplot3d/hist3d_demo.html
hist, xedges, yedges = np.histogram2d(date_array, event_array)
elements = (len(xedges)-1) * (len(yedges)-1)
xpos, ypos = np.meshgrid(xedges[:-1]+0.25, yedges[:-1]+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b')
xfmt = ticker.FuncFormatter(lambda x, pos: label_map[int(x)])
yfmt = mdates.DateFormatter('%m-%d')
zfmt = ticker.FuncFormatter(lambda z, pos: str(z))
ax.w_xaxis.set_major_formatter(xfmt)
ax.w_yaxis.set_major_formatter(yfmt)
ax.w_zaxis.set_major_formatter(zfmt)
ax.fmt_xdata = xfmt
ax.fmt_ydata = yfmt
ax.fmt_zdata = zfmt
plt.show()
答案 0 :(得分:1)
首先,你可能会改变你的xaxis格式化程序,当鼠标移到图表的边缘时,它会向解释器抛出很多异常:
你可以改变这个:
xfmt = ticker.FuncFormatter(lambda x, pos: label_map[int(x)])
对于这样的事情:
def xformatter(x,pos):
try:
val = label_map[int(x)]
except:
val = "None"
return val
...
xfmt = ticker.FuncFormatter(xformatter)
接下来,我发现实际mpl_toolkits.mplot3d
如果您查看\Lib\site-packages\mpl_toolkits\mplot3d\axis3d.py
你会发现这个错字:
class YAxis(Axis):
def get_data_interval(self):
'return the Interval instance for this axis data limits'
return self.axes.xy_dataLim.intervaly
class ZAxis(Axis):
def get_data_interval(self):
'return the Interval instance for this axis data limits'
return self.axes.zz_dataLim.intervalx
请注意self.axes.zz_dataLim.intervalx
应如何:self.axes.zz_dataLim.intervalz
您可能需要向开发人员报告这些问题。