【问题标题】:ggplotly - R, labeling trace namesggplotly - R,标记跟踪名称
【发布时间】:2015-11-12 22:47:51
【问题描述】:

我是 plotly 新手,无法找到有关如何命名迹线的相关文档,因此ggplotly 呈现的图中会出现一个有意义的标签。这是ggplotly site,其中显示了许多示例。在悬停时显示有意义的标签而不是后面跟 trace0、trace1 等的值需要什么。

例如,在第一个图中,标签如何出现以便显示:

比例:值

总账单:价值

理想情况下,我想直接在 R 中执行此操作,而不是通过 Web 界面。提前致谢。

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    使用 ggplot2 和 Plotly 你可以设置text。你会想要install Plotly and get a key。这里有两个例子。示例一:

    data(canada.cities, package="maps")
    viz <- ggplot(canada.cities, aes(long, lat)) +
        borders(regions="canada", name="borders") +
        coord_equal() +
        geom_point(aes(text=name, size=pop), colour="red", alpha=1/2, name="cities")
        ggplotly()
    
    ggplotly(filename="r-docs/canada-bubble")
    

    这会产生this plot,悬停时显示加拿大城市的名称。

    示例二:

    install.packages("gapminder")
    library(gapminder)
    
    ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = continent, text = paste("country:", country))) +
    geom_point(alpha = (1/3)) + scale_x_log10()  
    
    ggplotly(filename="ggplot2-docs/alpha-example")
    

    产生this plot

    有关更多信息,请参阅我们的R docsthis question,了解如何覆盖hover_text 元素。 Plotly 的原生 R API 允许您将 more controls 添加到您的绘图中。谢谢你问布赖恩。我们还将在我们的文档中添加一个新部分。免责声明:我为 Plotly 工作。

    【讨论】:

      【解决方案2】:

      您还可以在 ggplot2 转换之后编辑任何绘图图形属性,但您将其发送到绘图之前。 Here is an example 手动更改图例条目名称。我在这里重复一遍:

      df <- data.frame(x=c(1, 2, 3, 4), y=c(1, 5, 3, 5), group=c('A', 'A', 'B', 'B'))
      g <- ggplot(data=df, aes(x=x, y=y, colour=group)) + geom_point()
      
      # an intermediate step that `ggplotly` calls
      p <- plotly_build(g)
      
      # manually change the legend entry names, which are "trace0", "trace1" in your case
      p$data[[1]]$name <- 'Group A'
      p$data[[2]]$name <- 'Group B'
      
      # send this up to your plotly account
      p$filename <- 'ggplot2-user-guide/custom-ggplot2'
      plotly_POST(p)
      

      The extended example here 更详细地解释了它的工作原理和原因。

      请注意一般图例项目名称,例如“trace0”,将是您在数据框中分组的标签(如在 ggplot2 中)。

      【讨论】:

      • 我没有测试过这个例子,但我必须使用p$x$data[[1]]$name &lt;- 'Group A'。注意添加x
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多