交互式图表(工具提示):rCharts dimple plot:格式化轴

7
我是一位有用的助手,可以为您翻译文本。

我有一些使用ggplot2创建的图表,我想将它们嵌入到Web应用程序中:我想通过工具提示增强这些图表。我已经研究了几种选择。我目前正在尝试rCharts库以及其他一些库,比如dimple plots。

以下是原始的ggplot:

enter image description here

这是将其转换为一个dimple图的首次尝试:

enter image description here

我有几个问题:
  1. 在将y轴格式化为百分比后,数据被改变了。
  2. 在将x轴格式化为正确呈现日期后,打印的标签太多了。
我不限于使用dimple图表,如果有其他选项可以更轻松地调整轴格式,我很乐意知道。(Morris图表看起来也不错,但调整它们似乎更困难,对吗?)
目标:修复轴并添加工具提示,同时提供日期(格式为1984)和值(格式为40%)。
如果我能解决1和2,我会非常高兴。但是,如果有人有建议,这里还有另一个不那么重要的问题:
当悬停在线条上时,是否可以将“Top 10%”线标签添加到工具提示中?
从以下链接下载数据后:https://gist.github.com/ptoche/872a77b5363356ff5399,创建了一个数据框:
df <- read.csv("ps-income-shares.csv")

基本的 dimple 图表创建方式如下:

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个回答

6

这里有一种解决(1)和(2)的方法。参数showPercent不是为了将%添加到值中,而是重新计算值,使它们累加到100%,这就是为什么您看到了所指出的行为。

此时,您将看到我们仍然需要编写自定义javascript来调整x轴以使其按照我们想要的方式显示。在未来的迭代中,我们将努力允许整个dimple 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! - PatrickT
啊,我以为你已经做过了,因为你使用了afterScript - Ramnath
嗯,是的,但出于某种原因它需要一个刷新;-) - PatrickT
将上述代码包含到闪亮应用程序中是否存在特定的挑战?因为当直接在控制台中执行代码时,日期格式化可以正常工作,但在闪亮应用程序内执行时似乎无法正常工作。有什么想法吗?我应该发一个单独的问题来询问这个吗?谢谢。 - PatrickT
2
将你的闪亮应用程序代码放在gist中,并发布到rCharts的github问题中。 - Ramnath
1
添加了代码以完全复制ggplot2参考;正如@Ramnath所说,我们理解使这一过程变得更加容易的必要性。 - timelyportfolio

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

根据您使用的 rCharts 分支/版本,这可能有效或无效。最近是否使用过 devtools::install_github?如果是,则可能不起作用。我会尝试更新。 - timelyportfolio
可能是本地问题,因为今天我能够使用您发布的代码重现图形。我已删除我的评论。谢谢! - PatrickT
1
你的git链接似乎无法使用。我在想你是否已经将文件迁移到其他地方,因为基于纽约时报图表的惊人房价时间序列也出现了同样的问题。 然而,我下载了Patrick的数据,它完美地工作了。这非常有帮助,谢谢。 - Jon Nagra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接