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

查看:454
本文介绍了在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.

我已尝试添加transform属性:
.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位置吗?

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).

推荐答案

如果您设置了一个可以在Firebug中查看的变换旋转(180),它旋转元素相对于原点,而不是相对于文本锚点。因此,如果您的文本元素还有一个 x y 属性设置为它们定位,那么很可能是您在屏幕外旋转了文本。例如,如果您尝试过,

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>

另一种选择是使用可选的 cx 和参数指向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天全站免登陆