如何将X轴标签旋转到条形图上的条形? [英] How to rotate X-axis labels onto the bar in bar chart?

查看:273
本文介绍了如何将X轴标签旋转到条形图上的条形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对齐x轴标签,如下面的快照所示:

I need to align x-axis labels as shown in the snapshot below:

我试过:

.attr("transform", function(d) {
    return "rotate(-90)" 
})

但是它旋转了整个轴/刻度。

But it rotated the whole axis/scale.

如何解决这个问题?

jsFiddle

EDIT:
我更新了我的代码:

I updated my code:

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")  
.style("text-anchor", "end")
.attr("dx", "0em")
.attr("dy", "0em")
.attr("transform", function(d) {
    return "rotate(-90)" 
});

现在标签旋转到-90度。

Now the labels are rotated to -90 degrees. How do I get it onto the bars?

jsFiddle

推荐答案

我不太好用 translate 。但此 小费

I'm not that good in using translate. But this fiddle just works fine.

整个轴/标度旋转的原因是因为当使用 x y 位置,它的起点变为(0,0)

Reason why the whole axis/scale got rotated is because when the text being created with x and y position, the origin point of it becomes (0,0).

因此,要旋转文本标签,您需要使用 translate 而不是 x和y

So to rotate your text labels you need to position those text using translate instead of x and y.

fiddle 我在底部添加了以下代码,文本标签正在旋转。

In the fiddle I've added the below code at the bottom where it text labels are being rotated.

如果您想旋转它更多。您可以只更改轮播的程度。

If you wanted to rotate it more. You can just change the degree of rotation.


svg.selectAll(".text")
.data(data)
.enter()
.append("text")
.attr("transform", function(d, i) {
    return "translate(" + (35 + x(d.age)) + ", 250)" + "rotate(-90)"
})
.text(function(d) { return d.age; })

希望对你有帮助。

这篇关于如何将X轴标签旋转到条形图上的条形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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