如何用IronPython为Spotfire组合图独立Y轴设置数字格式类别?
解决Spotfire组合图Y轴格式切换失效问题
针对你在Spotfire 11.4中使用IronPython脚本切换Y轴格式时遇到的问题,核心原因是直接赋值IndexedRealFormatter的方式未正确关联到更新后的Y轴系列,且缺少对格式化器的必要参数配置。以下是修正后的脚本及说明:
修正后的脚本
import System from Spotfire.Dxp.Data import * from Spotfire.Dxp.Application.Visuals import * from Spotfire.Dxp.Data.Formatters import * # 获取组合图对象 viz = v.As[CombinationChart]() viz.YAxis.IndividualScaling = True # 获取当前文档属性值 metric = Document.Properties["MetricProperty"] # 根据属性值设置Y轴表达式 if metric == "A": viz.YAxis.Expression = 'Sum([A]) As [Total], Sum([A]) THEN [Value] / Sum([Value]) OVER (All([Axis.Color])) As [Percentage]' # 创建并配置左侧(Total)格式化器:货币格式 formatterTotal = DataType.Real.CreateFormatter() formatterTotal.Category = NumberFormatCategory.Currency formatterTotal.CurrencySymbol = "$" # 可根据需求修改货币符号 formatterTotal.Decimals = 2 # 创建并配置右侧(Percentage)格式化器:百分比格式 formatterPercentage = DataType.Real.CreateFormatter() formatterPercentage.Category = NumberFormatCategory.Percentage formatterPercentage.Decimals = 1 else: viz.YAxis.Expression = 'Avg([A percent]) As [Total], Avg([A percent]) THEN [Value] / Sum([Value]) OVER (All([Axis.Color])) As [Percentage]' # 两个系列都用百分比格式 formatterTotal = DataType.Real.CreateFormatter() formatterTotal.Category = NumberFormatCategory.Percentage formatterTotal.Decimals = 1 formatterPercentage = DataType.Real.CreateFormatter() formatterPercentage.Category = NumberFormatCategory.Percentage formatterPercentage.Decimals = 1 # 清除现有格式化配置,避免残留 viz.YAxis.Scale.Formatting.Clear() # 为每个系列关联对应的格式化器(关键:确保系列名称与表达式中的别名完全一致) viz.YAxis.Scale.Formatting.IndexedRealFormatter["Total"] = formatterTotal viz.YAxis.Scale.Formatting.IndexedRealFormatter["Percentage"] = formatterPercentage # 强制刷新视觉对象,确保格式生效 viz.Invalidate()
关键修改点说明
- 补全格式化器参数:原脚本仅设置了
Category,但未配置小数位数、货币符号等必要参数,导致格式显示异常或不生效。 - 强制刷新视觉对象:添加
viz.Invalidate()确保脚本修改后立即更新图表显示,避免手动设置后被默认值覆盖。 - 严格匹配系列名称:确保
IndexedRealFormatter的键名与Y轴表达式中定义的别名([Total]、[Percentage])完全一致,大小写敏感。 - 优化变量命名:将
formatterLeft/Right改为formatterTotal/Percentage,避免混淆系列对应关系。
额外注意事项
- 确保文档属性
MetricProperty的下拉选项值与脚本中的判断条件("A")完全匹配。 - 如果Y轴表达式修改后系列顺序变化,需确认系列名称的对应关系是否正确。
内容的提问来源于stack exchange,提问作者Mehrez
相关产品推荐
相关产品推荐

