javascript - D3 - 将 x 值数据刻度显示为百分比
问题描述
有一个如下所示的折线图:https : //imgur.com/1kadiJF 希望 x 轴在每个刻度后显示一个 & 符号,10%、20% 等。如何实现这一点?
我已经阅读了一种可以使用的格式方法,以及看到人们使用数学并实际进行转换,但我认为必须有一种快速的方法来在每个刻度后添加一个字符串 %,当然!
在这里使用 D3 的 V4
<script>
// set the dimensions and margins of the graph
const formatPercent = d3.format(".0%")
const margin = {top: 20, right: 30, bottom: 60, left: 250},
width = 1000 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// append the svg object to the body of the page
const svg = d3.select(".line")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Parse the Data
d3.json("./data/linedata.json", function(data) {
// Add X axis
const x = d3.scaleLinear()
.domain([0, 100])
.range([ 0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text").attr('class', 'xaxis')
.attr("transform", "translate(0,0 )")
.style("text-anchor", "end");
// Y axis
const y = d3.scaleBand()
.range([ 0, height ])
.domain(data.map(function(d) { return d.desc; }))
.padding(.1)
svg.append("g").attr('class', 'xaxis')
.call(d3.axisLeft(y))
//Bars
svg.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", x(0) )
.attr("y", function(d) { return y(d.desc); })
.attr("width", function(d) { return x(d.total); })
.attr("height", y.bandwidth() )
.attr("fill", "#008080")
})
</script>
解决方案
您是否尝试过使用 tickFormat 函数?像这样的东西应该工作:
.tickFormat(d => d + "%")
推荐阅读
- javascript - jstree 不是从提供的 json 创建树
- r - 清理推文以进行情绪分析
- akka-http - 在 akka-http 中,如何将路径段与可选的结束斜杠匹配?
- asp.net - 在 ASP.NET Core 应用程序中使用 Vue 切换
- ssl - cURL 错误 60:SSL 证书问题:证书已过期
- javascript - 显示/隐藏密码 onClick 使用 Vanilla js
- lwc - Lightning Web 组件反应性和非反应性属性
- r - r中数据框列表的总和行
- python - 基于 PySpark 数据帧中的相同列表更新多个列
- discord.py - 我如何做到这一点,以便我的机器人在 discord.py rewrite 中有 3 个警告时自动踢人