Plotly等高线图如何实现坐标轴刻度等间距分布而非按数值缩放
解决方法
你可以将数值坐标轴改为类别坐标轴,使用数组索引作为坐标值,再替换刻度文本为原始数值即可实现所有刻度等间距,修改后的完整代码如下:
import numpy as np import plotly.graph_objects as go Q_0 = [0.01, 0.02, 0.05, 0.08, 0.15, 0.4, 1., 5., 10., 20., 50.] w_0 = [0., 1., 2., 3., 4., 5., 8.,15] def f(q,w): return np.sqrt(q*w) x_idx = np.zeros([len(Q_0), len(w_0)]) y_idx = np.zeros([len(Q_0), len(w_0)]) z = np.zeros([len(Q_0), len(w_0)]) # 存储原始数值用于悬浮显示 x_original = np.zeros_like(x_idx) y_original = np.zeros_like(y_idx) for i, q in enumerate(Q_0): for j,w in enumerate(w_0): z[i,j] = f(q,w) x_idx[i,j] = i # 用索引作为坐标值,保证间距相等 y_idx[i,j] = j x_original[i,j] = q y_original[i,j] = w fig = go.Figure(go.Contour( x = x_idx.reshape(-1), y = y_idx.reshape(-1), z = z.reshape(-1), # 配置悬浮显示原始数值 customdata = np.stack((x_original.reshape(-1), y_original.reshape(-1)), axis=-1), hovertemplate = 'Q_0: %{customdata[0]}<br>w_0: %{customdata[1]}<br>z值: %{z:.2f}<extra></extra>', colorscale = 'Blues', contours = dict( showlabels = True, labelfont = dict( family = 'Raleway', color = 'white' ) ), hoverlabel = dict( bgcolor = 'white', bordercolor = 'black', font = dict( family = 'Raleway', color = 'black' ) ) )) fig.update_layout( xaxis_title="$Q_0$", yaxis_title="$w_0$", xaxis = dict( tickmode = 'array', tickvals = list(range(len(Q_0))), # 刻度位置对应索引 ticktext = [str(i) for i in Q_0] # 刻度文本显示原始数值 ), yaxis = dict( tickmode = 'array', tickvals = list(range(len(w_0))), ticktext = [str(i) for i in w_0] ) ) fig.show()
核心修改点
- 生成坐标时用
Q_0和w_0的索引作为x、y的坐标值,从根源上保证每个刻度的间距完全相等 - 坐标轴配置中,
tickvals对应索引值,ticktext保留原始数值标签,显示效果和需求完全一致 - 新增
customdata和hovertemplate配置,保证鼠标悬浮时显示原始的Q_0、w_0数值,不会出现显示索引的问题
内容的提问来源于stack exchange,提问作者jon
相关产品推荐
相关产品推荐

