ggplotly - R,标记跟踪名称

时间:2015-08-19 14:49:22

标签: r plotly

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

例如,在第一个图中,标签如何显示,如下所示:

比例:价值

总账单:价值

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

2 个答案:

答案 0 :(得分:9)

使用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,悬停时可以使用加拿大城市的名称。

enter image description here

示例二:

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

enter image description here

有关详细信息,请参阅我们的R docsthis question,了解如何覆盖hover_text元素。 Plotly的原生R API允许您将more controls添加到您的绘图中。谢谢你问Brian。我们也会在此向我们的文档添加新的部分。免责声明:我为Plotly工作。

答案 1 :(得分:4)

您还可以在 ggplot2转换之后编辑任何阴谋图形属性,但之前将其发送到plotly。 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中所示)。