rCharts nvd3 库强制刻度

2023-12-02

我想强制所有刻度线和刻度标签沿着轴出现rChartsn 绘图从nvd3图书馆。我尝试了几种方法但没有成功。

这是默认行为:

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

enter image description here

我想将所有数据放入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];
} !#")

enter image description here

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

为了给出成品的想法,这里有一个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()

enter image description here

以下是我根据我到处发现的一些建议尝试过的几件事:都不起作用。

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

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)

我也尝试结合tickValues and tickFormat但没有成功。

我也想过写一个剧本,但又是我的理解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>"
)

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


事实证明我没有正确设置tickValues因为我的语法与tickFormat。这是一个rCharts解决方案。相应的d3 or nvd3解应该很容易推导出来。

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 in tickValues but tickformat[x-1] in tickFormat.

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

rCharts nvd3 库强制刻度 的相关文章

随机推荐