You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ContEx库中将Y轴刻度标签从小数改为整数?

解决ContEx柱状图Y轴小数刻度转整数问题

你在Elixir项目中使用ContEx绘制柱状图时,需要将Y轴的小数刻度改为整数,找到的custom_value_formatter/2确实是合适的工具,下面是具体实现方法:

原代码

dataset = [
  ["Sage", scores.sage],
  ["Scientist", scores.scientist],
  ["Leader", scores.leader],
  ["Warrior", scores.warrior],
  ["Mother", scores.mother],
  ["Entrepreneur", scores.entrepreneur],
  ["Perfectionist", scores.perfectionist],
  ["Servant", scores.servant]
]

options = [
  custom_value_scale:
    Contex.ContinuousLinearScale.new()
      |> Contex.ContinuousLinearScale.domain(0, 56)
      |> Contex.Scale.set_range(0, 56),
  colour_palette: ["ffdfae"],
  data_labels: false,
]


Contex.Dataset.new(dataset)
|> Contex.Plot.new(Contex.BarChart, 550, 280, options)
|> Contex.Plot.to_svg()
|> elem(1)

修改方案

在options中添加custom_value_formatter配置,传入一个函数将数值格式化为整数:

options = [
  custom_value_scale:
    Contex.ContinuousLinearScale.new()
      |> Contex.ContinuousLinearScale.domain(0, 56)
      |> Contex.Scale.set_range(0, 56),
  colour_palette: ["ffdfae"],
  data_labels: false,
  # 添加Y轴刻度格式化函数
  custom_value_formatter: fn value, _axis ->
    Integer.to_string(trunc(value))
  end
]

说明

  • custom_value_formatter接收两个参数:刻度的数值value和轴信息_axis(这里用不到可以忽略)
  • 使用trunc/1截断小数部分得到整数,再转成字符串作为刻度显示文本
  • 如果需要四舍五入而不是截断,可以用round/1代替trunc/1

内容的提问来源于stack exchange,提问作者Sangeetha ilango

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:10:57