最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - d3 - Rotate x-axis labels - Stack Overflow

programmeradmin1浏览0评论

I'm trying this graph:

with my data.

I wanted to rotate the x-axis labels.

Here's the code :

var timeLabels = svg.selectAll(".timeLabel")
          .data(times)
          .enter().append("text")
            .text(function(d) { return d; })
            .attr("x", function(d, i) { return i * gridSize; })
            .attr("y", 0)
            .style("text-anchor", "end")
            .attr("transform", "translate(" + gridSize / 2 + ", -6)rotate(-90)")
            .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });

But the result I get is. Entire labels get rotated to -90 deg in a single straight line. Instead I wanted each label to be rotated to -90 deg. Like this:

I even tried using .attr("transform", function(d) {return "translate(" + gridSize / 2 + ", -6)rotate(-90)"}) but it didn't help.

Result :

Help will be very much pleased.

I'm trying this graph:

with my data.

I wanted to rotate the x-axis labels.

Here's the code :

var timeLabels = svg.selectAll(".timeLabel")
          .data(times)
          .enter().append("text")
            .text(function(d) { return d; })
            .attr("x", function(d, i) { return i * gridSize; })
            .attr("y", 0)
            .style("text-anchor", "end")
            .attr("transform", "translate(" + gridSize / 2 + ", -6)rotate(-90)")
            .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });

But the result I get is. Entire labels get rotated to -90 deg in a single straight line. Instead I wanted each label to be rotated to -90 deg. Like this:

I even tried using .attr("transform", function(d) {return "translate(" + gridSize / 2 + ", -6)rotate(-90)"}) but it didn't help.

Result :

Help will be very much pleased.

Share edited Jan 18, 2014 at 4:03 user3206082 asked Jan 17, 2014 at 13:32 user3206082user3206082 43110 silver badges18 bronze badges 2
  • 1 Have you seen this tutorial? – Lars Kotthoff Commented Jan 17, 2014 at 14:45
  • Yea i tried but the result is not what i expected. I'll post the image. – user3206082 Commented Jan 18, 2014 at 4:01
Add a ment  | 

2 Answers 2

Reset to default 9

The problem is that when you rotate an element, it gets rotated around the origin point, (0,0), of the local coordinate system. If the element you're rotating isn't right next to the origin, it can end up moved quite a large distance, and possibly moved outside the chart altogether.

There are two ways you can fix it:

  1. Position the label with a "transform" attribute instead of with x and y attributes. That way, the label's coordinate system -- including the (0,0) point of rotation -- will be positioned with it, and the rotation will happen where you expect. The code @Manoj gave follows that system, but assumes you are using the default xAxis function. For your custom axis label code, your labels are given a y value of 0, and an x value determined from a function. You just need to move those values into the transform attribute, paying careful attention that the transformation of the overall position es before the rotation and adjustment:

    var timeLabels = svg.selectAll(".timeLabel")
      .data(times)
      .enter().append("text")
        .text(function(d) { return d; })
        .attr("transform", function(d, i) { 
              return "translate(" + ( i * gridSize) + ",0)"
                      + "translate(" + gridSize / 2 + ", -6)rotate(-90)";
         } )
        .style("text-anchor", "end")
        .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? 
                                   "timeLabel mono axis axis-worktime" : 
                                   "timeLabel mono axis"); 
         });
    

    Of course, you could bine those two translation statements, as:

        .attr("transform", function(d, i) { 
              return "translate(" + ( (i + 0.5) * gridSize) + ",-6)"
                      + "rotate(-90)")
    
  2. Alternately, you can specify a center of rotation in the rotate statement, by including the x and y values of the point you want it to rotate around:

    var timeLabels = svg.selectAll(".timeLabel")
      .data(times)
      .enter().append("text")
        .text(function(d) { return d; })
        .attr("x", function(d, i) { return i * gridSize; })
        .attr("y", 0)
        .attr("transform", function(d, i) { 
              return "translate(" + gridSize / 2 + ", -6)" +
                     "rotate(-90 "+ ((i + 0.5) * gridSize) + " " + (-6) +")";
         } )
        .style("text-anchor", "end")
        .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? 
                                   "timeLabel mono axis axis-worktime" : 
                                   "timeLabel mono axis"); 
         });
    

    As you can see, this version is rather repetitive, as we have to calculate the position of the label twice -- once to position it, and once to set the center of rotation. You can see why most examples (and the d3 axis functions) position the labels with translations, so they can just be rotated in place.

Try this code:

Fiddle:

 svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("id", "x")
    .attr("transform", "translate(0," + (h) + ")")
    .call(xAxis)
    .selectAll("text")
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", function (d) {
    return "rotate(-90)";
});
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>