R:交互式图(工具提示):rCharts凹坑图:格式化轴

时间:2014-05-04 22:31:24

标签: r ggplot2 rcharts morris.js dimple.js

我有一些使用ggplot2创建的图表,我想将其嵌入到网络应用程序中:我想用工具提示来增强图表。我已经研究了几种选择。我目前正在试验rCharts库,其中包括凹坑图。

这是原始的ggplot:

enter image description here

这是第一次尝试将其转换为凹坑图:

enter image description here

我有几个问题:

  1. 在用百分比格式化y轴后,数据会被更改。

  2. 格式化x轴以正确渲染日期后,会打印太多标签。

  3. 我不喜欢凹陷图表,所以如果有其他选项可以更容易地调整轴格式,我很高兴知道。 (莫里斯图表看起来也不错,但调整它们看起来更难,不是吗?)

    目标:修复轴并添加提供日期(格式为1984)和值(格式为40%)的工具提示。

    如果我可以修复1和2,我会非常高兴。但这是另一个不太重要的问题,以防有人提出建议:

    将鼠标悬停在线条上时,是否可以将线条标签("前10%")添加到工具提示中?

    https://gist.github.com/ptoche/872a77b5363356ff5399下载数据后, 创建数据框:

    df <- read.csv("ps-income-shares.csv")
    

    基本凹坑图用:

    创建
    library("rCharts")
    p <- dPlot(
        value ~ Year,
        groups = c("Fractile"),
        data = transform(df, Year = as.character(format(as.Date(Year), "%Y"))),
        type = "line",
        bounds = list(x = 50, y = 50, height = 300, width = 500)
    )
    
    虽然基本,但到目前为止还不错。但是,以下用于将y数据转换为百分比的命令会更改数据:

    p$yAxis(type = "addMeasureAxis", showPercent = TRUE)
    

    showPercent我做错了什么?

    供参考,这是ggplot代码:

    library("ggplot2")
    library("scales")
    p <- ggplot(data = df, aes(x = Year, y = value, color = Fractile))
    p <- p + geom_line()
    p <- p + theme_bw()
    p <- p + scale_x_date(limits = as.Date(c("1911-01-01", "2023-01-01")), labels = date_format("%Y"))
    p <- p + scale_y_continuous(labels = percent)
    p <- p + theme(legend.position = "none")
    p <- p + geom_text(data = subset(df, Year == "2012-01-01"), aes(x = Year, label = Fractile, hjust = -0.2), size = 4)
    p <- p + xlab("")
    p <- p + ylab("")
    p <- p + ggtitle("U.S. top income shares (%)")
    p
    

    有关信息,上图基于 Thomas Piketty Emmanuel Saez 在他们对美国最高收入的研究中汇总的数据。数据和更多数据可以在他们的网站上找到,例如

    http://elsa.berkeley.edu/users/saez/

    http://piketty.pse.ens.fr/en/

    修改

    这是Ramnath的解决方案的屏幕截图,添加了标题并调整了轴标签。谢谢Ramnath!

    p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y')
    p$yAxis(outputFormat = "%")
    p$setTemplate(afterScript = "
      <script>
        myChart.axes[0].timeField = 'Year'
        myChart.axes[0].timePeriod = d3.time.years
        myChart.axes[0].timeInterval = 10
        myChart.draw()
        myChart.axes[0].titleShape.remove()  // remove x label
        myChart.axes[1].titleShape.remove()  // remove y label
        myChart.svg.append('text')           // chart title
            .attr('x', 40)
            .attr('y', 20)
            .text('U.S. top income shares (%)')
            .style('text-anchor','beginning')
            .style('font-size', '100%')
            .style('font-family','sans-serif')
      </script>               
    ")
    p
    

    enter image description here

    更改(而不是删除)轴标签,例如:

    myChart.axes[1].titleShape.text('Year')
    

    在图中添加图例:

    p$set(width = 1000, height = 600)
    p$legend(
      x = 580,
      y = 0,
      width = 50,
      height = 200,
      horizontalAlign = "left"
    )
    

    保存rchart:

    p$save("ps-us-top-income-shares.html", cdn = TRUE)
    

    可以获得基于nvd3库的替代方案(没有任何花哨的东西):

    df$Year <- strftime(df$Year, format = "%Y")
    n <- nPlot(data = df, value ~ Year, group = 'Fractile', type = 'lineChart')
    

2 个答案:

答案 0 :(得分:6)

这是解决(1)和(2)的一种方法。参数showPercent不是为值添加%,而是重新计算值,使它们最多叠加100%,这就是您看到指出的行为的原因。

此时,您将看到我们仍然需要编写自定义javascript来调整x轴以使其显示我们想要的方式。在将来的迭代中,我们将努力允许在rCharts中访问整个dimple API。

df <- read.csv("ps-income-shares.csv")
p <- dPlot(
  value ~ Year,
  groups = c("Fractile"),
  data = df,
  type = "line",
  bounds = list(x = 50, y = 50, height = 300, width = 500)
)
p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y')
p$yAxis(outputFormat = "%")
p$setTemplate(afterScript = "
  <script>
     myChart.axes[0].timeField = 'Year'
     myChart.axes[0].timePeriod = d3.time.years
     myChart.axes[0].timeInterval = 5
     myChart.draw()

     //if we wanted to change  our line width to match the ggplot chart
     myChart.series[0].shapes.style('stroke-width',1);

   </script>
")
p

答案 1 :(得分:4)

rCharts正在迅速发展。我知道它已经晚了,但是如果有人想看到它,这里几乎完全复制了所显示的ggplot样本。

  #For information, the chart above is based
  #on the data put together by Thomas Piketty and Emmanuel Saez
  #in their study of U.S. top incomes.
  #The data and more may be found on their website, e.g.
  #http://elsa.berkeley.edu/users/saez/
  #http://piketty.pse.ens.fr/en/

  #read in the data
  df <- read.csv(
    "https://gist.githubusercontent.com/ptoche/872a77b5363356ff5399/raw/ac86ca43931baa7cd2e17719025c8cde1c278fc1/ps-income-shares.csv",
    stringsAsFactors = F
  )

  #get year as date
  df$YearDate <- as.Date(df$Year)

  library("ggplot2")
  library("scales")
  p <- ggplot(data = df, aes(x = YearDate, y = value, color = Fractile))
  p <- p + geom_line()
  p <- p + theme_bw()
  p <- p + scale_x_date(limits = as.Date(c("1911-01-01", "2023-01-01")), labels = date_format("%Y"))
  p <- p + scale_y_continuous(labels = percent)
  p <- p + theme(legend.position = "none")
  p <- p + geom_text(data = subset(df, Year == "2012-01-01"), aes(x = YearDate, label = Fractile, hjust = -0.2), size = 4)
  p <- p + xlab("")
  p <- p + ylab("")
  p <- p + ggtitle("U.S. top income shares (%)")
  gp <- p
  gp


  p <- dPlot(
    value ~ Year,
    groups = c("Fractile"),
    data = df,
    type = "line",
    bounds = list(x = 50, y = 50, height = 300, width = 500)
  )
  p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y')
  p$yAxis(outputFormat = "%")
  p$setTemplate(afterScript = "
    <script>
       myChart.axes[0].timeField = 'Year'
       myChart.axes[0].timePeriod = d3.time.years
       myChart.axes[0].timeInterval = 5
       myChart.draw() 

       //if we wanted to change  our line width to match the ggplot chart
       myChart.series[0].shapes.style('stroke-width',1);

      //to take even one step further
      //we can add labels like in the ggplot example
      myChart.svg.append('g')
        .selectAll('text')
        .data(
          d3.nest().key(function(d){return d.cx}).map(myChart.series[0]._positionData)[myChart.axes[0]._max])
        .enter()
          .append('text')
          .text(function(d){return d.aggField[0]})
          .attr('x',function(d){return myChart.axes[0]._scale(d.cx)})
          .attr('y',function(d){return myChart.axes[1]._scale(d.cy)})
          .attr('dy','0.5em')
          .style('font-size','80%')
          .style('fill',function(d){return myChart._assignedColors[d.aggField[0]].fill})
     </script>
  ")
  p$defaultColors(ggplot_build(gp)$data[[2]]$colour)
  p