R:交互式图(工具提示):rCharts浅凹图:格式化轴 [英] R: interactive plots (tooltips): rCharts dimple plot: formatting axis

查看:146
本文介绍了R:交互式图(工具提示):rCharts浅凹图:格式化轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



以下是原始ggplot:


这是第一次尝试将其转换为一个凹坑情节:





我有几个问题:在用百分比格式化y轴后,数据会发生变化。


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



  2. 我没有与凹坑图表绑定,所以如果还有其他选项允许更简单的调整轴格式,我很乐意知道。 (Morris图表看起来不错,但调整它们看起来更难,不是吗?)



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

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

    当将鼠标悬停在工具提示上时,可以将线条标签(前10%)行吗?



    从以下网址下载数据后: https ://gist.github.com/ptoche/872a77b5363356ff5399
    a数据框被创建:


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

    (b
    $ b $ p $ library(rCharts)
    p < - dPlot(
    value〜年份,
    groups = c(Fractile),
    data = transform(df,Year = as.character(格式(as.Date(Year),%Y))),
    type =line,
    bounds = list(x = 50,y = 50,height = 300,width = 500)

    pre>

    基本的,迄今为止非常好。但是,下面的命令旨在将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), (美元)美元最高收入份额(%)美元最高收入份额(%)美元最高收入份额(美元) ))
    p

    有关信息,上面的图表基于 Thomas Piketty Emmanuel Saez 在研究美国最高收入时的数据。这些数据及更多信息可以在他们的网站上找到,例如

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



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



    编辑:

    下面是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()//移除x标签
    myChart.axes [1] .titleShape.remove()//移除标签
    myChart.svg.append('text')//图表标题$ ('美国最高收入份额(%)')
    .attr('x',40)
    .attr('y',20)
    .text('
    .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,
    horizo​​ntalAlign =left



    $ b

    保存rchart:

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



    <

      df $年份< p>一个基于nvd3库的替代方案可以获得(没有任何花哨的东西) ;  -  strftime(df $ Year,format =%Y)
    n < - nPlot(data = df,value〜Year,group ='Fractile',type ='lineChart')


    解决方案

    这是解决(1)和(2)的一种方法。参数 showPercent 不是为这些值添加%,而是为了重新计算这些值,以便它们叠加到100%,这就是为什么你看到了你指出的行为。

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

      df<  -  read.csv (ps-income-shares.csv)
    p <-dPlot(
    值〜年,
    组= c(分值),
    数据= 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()

    //如果我们想改变线宽以匹配ggplot图表
    myChart.series [0] .shapes.style('stroke-width',1);

    < / script>

    p


    I have some charts created with ggplot2 which I would like to embed in a web application: I'd like to enhance the plots with tooltips. I've looked into several options. I'm currently experimenting with the rCharts library and, among others, dimple plots.

    Here is the original ggplot:

    Here is a first attempt to transpose this to a dimple plot:

    I have several issues:

    1. after formatting the y-axis with percentages, the data is altered.

    2. after formatting the x-axis to correctly render dates, too many labels are printed.

    I am not tied to dimple charts, so if there are other options that allow for an easier way to tweak axis formats I'd be happy to know. (the Morris charts look nice too, but tweaking them looks even harder, no?)

    Objective: Fix the axes and add tooltips that give both the date (in the format 1984) and the value (in the format 40%).

    If I can fix 1 and 2, I'd be very happy. But here is another, less important question, in case someone has suggestions:

    Could I add the line labels ("Top 10%") to the tooltips when hovering over the lines?

    After downloading the data from: https://gist.github.com/ptoche/872a77b5363356ff5399, a data frame is created:

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

    The basic dimple plot is created with:

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

    While basic, so far so good. However, the following command, intended to convert the y-data to percentages, alters the data:

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

    What am I doing wrong with showPercent?

    For reference, here is the ggplot code:

    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
    

    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/

    EDIT:

    Here is a screenshot of Ramnath's solution, with a title added and axis labels tweaked. Thanks 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
    

    To change (rather than remove) axis labels, for instance:

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

    To add a legend to the plot:

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

    To save the rchart:

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

    An alternative based on the nvd3 library can be obtained (without any of the fancy stuff) with:

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

    解决方案

    Here is one way to solve (1) and (2). The argument showPercent is not to add % to the values, but to recompute the values so that they stack up to 100% which is why you are seeing the behavior you pointed out.

    At this point, you will see that we are still having to write custom javascript to tweak the x-axis to get it to display the way we want it to. In future iterations, we will strive to allow the entire dimple API to be accessible within 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
    

    这篇关于R:交互式图(工具提示):rCharts浅凹图:格式化轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆