javascript 将 y 轴显示为百分比?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10201841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display y-axis as percentages?
提问by grautur
I'm making a chart, and I want my y-axis tick labels to display as percentages (instead of decimals). How can I do this?
我正在制作图表,我希望我的 y 轴刻度标签显示为百分比(而不是小数)。我怎样才能做到这一点?
My current code looks something like
我当前的代码看起来像
yAxis
.append("text")
.attr("class", "ticklabel")
.attr("x", 0)
.attr("y", y)
.attr("dy", ".5em")
.attr("text-anchor", "middle")
.text(y.tickFormat(5))
.attr("font-size", "10px")
I noticed that d3 has a format specifier, but I'm not sure how to use these in conjunction with tickFormat
.
我注意到 d3 有一个格式说明符,但我不确定如何将它们与tickFormat
.
回答by mbostock
It looks like you authoring the axis by hand. I recommend using the d3.svg.axiscomponent instead, which does the rendering for you. For example:
看起来您是手动创作轴的。我建议改用d3.svg.axis组件,它会为您进行渲染。例如:
If you want to format ticks as percentages, then use d3.format's %directive:
如果要将刻度格式化为百分比,请使用d3.format的%指令:
var formatPercent = d3.format(".0%");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent);
You can instead use the pdirective if you want to round to the percentage to significant digits.
如果要将百分比四舍五入为有效数字,则可以改用p指令。
To answer your question more directly, you use d3.format instead ofthe scale's tickFormat. Scales provide a default tickFormat for convenience, but if you want different behavior, then you use a custom d3.format rather than the scale's default one.
要更直接地回答您的问题,您可以使用 d3.format而不是秤的 tickFormat。为方便起见,Scales 提供了默认的 tickFormat,但如果您想要不同的行为,那么您可以使用自定义 d3.format 而不是比例的默认格式。