Holoviews/Bokeh:调整y轴维度排序无效果,负数值未向下排列
解决Holoviews热力图Y轴排序问题
问题描述
尝试重新排序热力图的Y轴,使其从0到-19在X轴下方(负数值向下递减),但无论通过redim.values设置何种排序顺序,Y轴始终从0到-19向上排列。
问题原因
- 数据中
y列存储为字符串类型,Holoviews将其识别为分类变量,分类轴默认从下往上排列,redim.values仅指定分类项顺序,无法改变轴的整体方向。 - Bokeh渲染器的分类轴默认方向为递增向上,需显式调整才能实现负数值向下的排列逻辑。
解决方案
方案1:转为数值轴并反转方向(推荐)
将y列改为数值类型,直接通过反转Y轴实现需求,逻辑更直观:
from pathlib import Path import holoviews as hv import pandas as pd import webbrowser hv.extension('bokeh') renderer = hv.renderer('bokeh') # 修改:y存储为数值而非字符串 data = [{"x": str(i), "y": -j, "z": i*j } for i in range(20) for j in range(20)] df = pd.DataFrame(data) x_vals = list(set(df["x"].tolist())) x_vals.sort(key=int) hm = hv.HeatMap(df) # 关键:添加invert_yaxis=True反转Y轴 hm.opts( hv.opts.HeatMap( tools=['hover'], colorbar=True, height=800, width=800, toolbar='above', invert_yaxis=True # 让数值大的0在顶部,小的-19在底部 ) ) html = renderer.html(hm) Path("test_fixed.html").write_text(html, encoding="utf-8") webbrowser.open("test_fixed.html")
方案2:保留字符串类型,调整分类轴
若必须保留y的字符串格式,可通过反向分类范围实现:
from pathlib import Path import holoviews as hv import pandas as pd import webbrowser hv.extension('bokeh') renderer = hv.renderer('bokeh') data = [{"x": str(i), "y": str(-j), "z": i*j } for i in range(20) for j in range(20)] df = pd.DataFrame(data) x_vals = list(set(df["x"].tolist())) x_vals.sort(key=int) # 按数值排序Y的字符串值,0在最前,-19在最后 y_vals = sorted(df["y"].unique(), key=lambda x: int(x), reverse=True) hm = hv.HeatMap(df).redim.values(y=y_vals) # 关键:使用反向分类Y轴范围 hm.opts( hv.opts.HeatMap( tools=['hover'], colorbar=True, height=800, width=800, toolbar='above', y_range=hv.CategoricalYReverse(y_vals) ) ) html = renderer.html(hm) Path("test_fixed_str.html").write_text(html, encoding="utf-8") webbrowser.open("test_fixed_str.html")
说明
- 方案1逻辑简单,数值轴的行为更符合日常对正负数值的认知,优先选用。
- 方案2适用于Y轴必须为字符串分类的特殊场景,通过
CategoricalYReverse直接定义分类轴的显示顺序。
内容的提问来源于stack exchange,提问作者Amiga500
相关产品推荐
相关产品推荐

