javascript - rCharts 格式化轴标签 : outputFormat

标签 javascript r d3.js rcharts nvd3.js

考虑从 rCharts/NVD3 示例页面中提取的图

p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
p6

我试图让我的 y 轴显示百分比,所以我尝试了以下代码(在 R: interactive plots (tooltips): rCharts dimple plot: formatting axis 之后)但它返回一个空白页

p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
p6$yAxis(outputFormat = "%")
p6

我做了一些研究并得到了以下结果:

p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
p6$yAxis(tickFormat = "#! function(d) {return d*100 + '%' } !#")
p6

现在,我知道 0 个 javascript,并希望尽可能多地使用 R,至少在短期内如此。谁能告诉我

  1. 为什么第一种方法不起作用,以及
  2. 第二种方法是否是最好的方法

最佳答案

由于问题 1 的答案在@jdharrison 的评论中,我想我会用完整的代码示例快速回答问题 2,并在评论中展示实现同一目标的不同方法。

  #turn off rstudio viewer
  #since we will be making lots of charts
  #we'll turn it back on at end
  oldviewer = options("viewer")
  options(viewer=NULL)

  data(economics, package = "ggplot2")

  #if we know we would like percent
  #and R is our friend but javascript is not
  #we could do some transformation in R
  economics$uempmed <- economics$uempmed/100

  p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
  p6
  #then we could use d3.format just like the dimple example
  #except dimple assumes the d3.format part so we just need "%"
  #see https://github.com/PMSI-AlignAlytics/dimple/wiki/dimple.axis#tickFormat
  #for more on d3.format
  #see https://github.com/mbostock/d3/wiki/Formatting#d3_format
  p6$yAxis( tickFormat = "#!d3.format('%')!#" )
  p6

  #however your method works fine also
  p6$yAxis(tickFormat = "#! function(d) {return d*100 + '%' } !#")
  p6

  #but let's say we did not do the above transform
  #dividing by 100
  #here is how we could do it in javascript
  data(economics, package = "ggplot2")
  p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
  p6$yAxis(tickFormat = "#! function(d) {
    //will change to .2% to show how to get two decimal
   return d3.format('.2%')(d/100)
  } !#")
  p6

  #turn rstudio viewer back on
  options(viewer = oldviewer)

关于javascript - rCharts 格式化轴标签 : outputFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663820/

相关文章:

javascript - 无法通过javascript将href和class添加到列表项

regex - 列出 R 中不匹配模式的文件

r - 使用 ggplot2 创建函数

javascript - 在 d3.js 的一列中查找最大值

d3.js - D3js:什么时候使用.datum()和.data()?

javascript - 按点击 Javascript 的顺序打印所有按钮

javascript - 将此 jQuery 片段转换为普通 javascript(焦点不起作用)

javascript - Knockout.js 复选框的双向绑定(bind)不起作用

r - R 中的函数返回网络中的祖先和子代

javascript - d3 : Appending multiple elements based on integer in data