【问题标题】:R: interactive plots (tooltips): rCharts dimple plot: formatting axisR:交互式绘图(工具提示):rCharts 酒窝绘图:格式化轴
【发布时间】:2014-05-04 22:31:24
【问题描述】:

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

这是原始的ggplot:

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

我有几个问题:

  1. 在用百分比格式化 y 轴后,数据会发生变化。

  2. 在格式化 x 轴以正确呈现日期后,打印的标签过多。

我不依赖于凹坑图表,所以如果有其他选项可以更轻松地调整轴格式,我很乐意知道。 (莫里斯图表看起来也不错,但调整它们看起来更难,不是吗?)

目标:修复坐标轴并添加提供日期(格式为 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 PikettyEmmanuel Saez 在他们对美国最高收入者的研究中汇总的数据。数据等可以在他们的网站上找到,例如

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

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

编辑:

这是 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

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

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')

【问题讨论】:

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


    【解决方案1】:

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

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

    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
    

    【讨论】:

    • 我需要更新 devtools::install_github("rCharts", "ramnathv", ref = "dev"),非常好,感谢 Ramnath!
    • 啊。我假设你已经这样做了,因为你使用的是afterScript
    • 嗯,是的,但由于某种原因,它需要复习;-)
    • 将您闪亮的应用程序代码放在一个要点中并发布到 rCharts 的 github 问题。
    • 添加了完全复制 ggplot2 参考的代码;正如@Ramnath 所说,我们理解让这一切变得更容易的必要性
    【解决方案2】:

    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
    

    【讨论】:

    • 取决于您使用的rCharts 的分支/版本,这可能会或可能不会起作用。你有一段时间devtools::install_github了吗?如果是这样,这可能行不通。我会努力更新的。
    • 这一定是本地问题,因为今天我能够使用您发布的代码重现情节。我删除了我的cmets。谢谢!
    • 您的 git 链接似乎不起作用。我想知道您是否已将文件迁移到其他地方,因为基于您所做的 NYT 图表的惊人房价时间序列也发生了同样的情况。但是,我下载了帕特里克的数据,它运行良好。非常有帮助,谢谢。
    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多