【问题标题】:rCharts nvd3 library force ticksrCharts nvd3 库强制刻度
【发布时间】:2015-01-15 18:48:49
【问题描述】:

我想强制所有刻度线和刻度线标签沿轴显示在来自nvd3 库的rCharts nPlot 中。我尝试了几种方法都没有成功。

这是默认行为:

df <- data.frame(x = 1:13, y = rnorm(13))
library(rCharts)
n <- nPlot(data = df, y ~ x, type = 'lineChart')
n$yAxis(showMaxMin = FALSE)

我想让1:13 中的所有数据沿 x 轴显示。

最后,我想用以下替换显示等距的自定义刻度:

n$xAxis(tickFormat = "#! function (x) { 
    ticklabels = ['0-1000', '1000-1500', '1500-1700', '1700-1820', '1820-1913', 
        '1913-1950', '1950-1970', '1970-1990', '1990-2012', '2012-2030', 
        '2030-2050', '2050-2070', '2070-2100']
        return ticklabels[x-1];
} !#")

我希望清楚我为什么要打印所有刻度线和标签(并且等距)。

为了给出成品的想法,这里是ggplot2 印象:

library(ggplot2)
df <- data.frame(x = c('0-1000', '1000-1500', '1500-1700', '1700-1820', '1820-1913', 
    '1913-1950', '1950-1970', '1970-1990', '1990-2012', '2012-2030', '2030-2050', 
    '2050-2070', '2070-2100'), y = rnorm(13), z = "group1")
ggplot(data = df, aes(x = x, y = y, group = z)) + geom_line()

根据我在这里和那里找到的一些建议,我尝试了以下几件事:两者都不起作用。

根据我对文档的阅读,我认为这可行:

n$xAxis(tickFormat = "#! function (x) {
  return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13][x-1];
} !#")

我也试过这个,碰巧:

n$xAxis(ticks = 13)

我也尝试将tickValuestickFormat 合并,但没有成功。

我也想过写一个脚本,但是我对nvd3库的理解又不够。

n$setTemplate(afterScript = 
    "<script>
        var chart = nv.models.lineChart();
        var newAxisScale = d3.scale.linear();
            .range(d3.extent(chart.axes[0]._scale.range()))
            .domain([1, d3.max(chart.axes[0]._scale.domain())])
        chart.axes[0].shapes.call(
            d3.svg.axis()
            .orient('bottom')
            .scale(newAxisScale)
            .ticks(13)
            //.tickValues()
            //.tickFormat(d3.format())
        ).selectAll('text')
          .attr('transform','')
    </script>"
)

这些都不会在控制台中报告错误,但它们都不会修改上面第一个图的外观。

【问题讨论】:

标签: r d3.js nvd3.js rcharts


【解决方案1】:

事实证明我没有正确设置tickValues,因为我将语法与tickFormat 混淆了。这是一个rCharts 解决方案。对应的d3nvd3 解应该很容易推导出来。

n <- nPlot(data = df, y ~ x, type = 'lineChart')
n$yAxis(showMaxMin = FALSE)
n$addParams(height = 500, width = 1000)
n$xAxis(tickValues = "#! function (x) {    
    tickvalues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
    return tickvalues;
} !#")
n$xAxis(tickFormat = "#! function (x) {
    tickformat = ['0-1000', '1000-1500', '1500-1700', '1700-1820', '1820-1913', 
       '1913-1950', '1950-1970', '1970-1990', '1990-2012', '2012-2030', '2030-2050', 
       '2050-2070', '2070-2100'];
    return tickformat[x-1];
} !#")
n

注意代码是如何在tickValues 中具有tickvalues 而在tickFormat 中具有tickformat[x-1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多