在 d3 中旋转 x 轴文本 [英] rotate x axis text in d3

查看:34
本文介绍了在 d3 中旋转 x 轴文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 d3 和 svg 编码的新手,正在寻找一种在图表的 xAxis 上旋转文本的方法.我的问题是 xAxis 标题通常比条形图中的条宽.所以我希望旋转文本以在 xAxis 下方垂直(而不是水平)运行.

I am new to d3 and svg coding and am looking for a way to rotate text on the xAxis of a chart. My problem is that typically the xAxis titles are longer than the bars in the bar chart are wide. So I'm looking to rotate the text to run vertically (rather than horizontally) beneath the xAxis.

我尝试添加转换属性:.attr("transform", "rotate(180)")

I've tried adding the transform attribute: .attr("transform", "rotate(180)")

但是当我这样做时,文本完全消失了.我试过增加 svg 画布的高度,但仍然无法查看文本.

But when I do that, the text disappears altogether. I've tried increasing the height of the svg canvas, but still was unable to view the text.

任何关于我做错了什么的想法都会很棒.我还需要调整 x 和 y 位置吗?以及,如果是这样,多少(当我在 Firebug 中看到它时很难进行故障排除).

Any thoughts on what I'm doing wrong would be great. Do I need to also adjust the x and y positions? And, if so, by how much (hard to troubleshoot when I can see it in Firebug).

推荐答案

如果设置了rotate(180) 的变换,它会相对于原点旋转元素,而不是相对于文本锚点.因此,如果您的文本元素还设置了 xy 属性来定位它们,则很可能您已将文本旋转到屏幕外.例如,如果您尝试过,

If you set a transform of rotate(180), it rotates the element relative to the origin, not relative to the text anchor. So, if your text elements also have an x and y attribute set to position them, it’s quite likely that you’ve rotated the text off-screen. For example, if you tried,

<text x="200" y="100" transform="rotate(180)">Hello!</text>

文本锚点将在⟨-200,100⟩.如果你想让文本锚点停留在⟨200,100⟩,那么你可以在旋转之前使用变换来定位文本,从而改变原点.

the text anchor would be at ⟨-200,100⟩. If you want the text anchor to stay at ⟨200,100⟩, then you can use the transform to position the text before rotating it, thereby changing the origin.

<text transform="translate(200,100)rotate(180)">Hello!</text>

另一种选择是对 SVG 的 旋转变换,以便您可以指定旋转的原点.这最终有点多余,但为了完整性,它看起来像这样:

Another option is to use the optional cx and cy arguments to SVG’s rotate transform, so that you can specify the origin of rotation. This ends up being a bit redundant, but for completeness, it looks like this:

<text x="200" y="100" transform="rotate(180,200,100)">Hello World!</text>

这篇关于在 d3 中旋转 x 轴文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆