如何将文本添加到胚芽和ggplotly?

时间:2019-03-06 07:33:23

标签: r ggplot2 plotly

我想将文本添加到图中。例如,代码无法将mytext添加到ply.test图?任何人都可以提供帮助。谢谢!

test.dat <- data.frame(xmin=c(0,1.5), ymin=c(-1,-1), xmax=c(1,2), ymax=c(1,1),        col=c("blue", "red"))
ggp.test <- ggplot() + geom_rect(data=test.dat, aes(xmin=xmin, ymin=ymin,    xmax=xmax, ymax=ymax, group = col), fill=test.dat$col) + theme_bw()
ggp.test

# How to add the text as hoverinfo?
ply.test <- plotly_build(ggp.test)
ply.test
mytext <- paste(test.dat$xmin,test.dat$ymin,sep = "")
style(ply.test, text = mytext, hoverinfo = "text", traces = c(0,1 ))

1 个答案:

答案 0 :(得分:0)

以下代码对我有用:

library(plotly)

test.dat <- data.frame(
 xmin=c(0,1.5), xmax=c(1,2),
 ymin=c(-1,-1), ymax=c(1,1), col=c("blue", "red") )

ggp.test <- ggplot(data=test.dat, 
 aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, group = col) ) +
  geom_rect(fill=test.dat$col) +
  theme_bw()

ply.test <- plotly_build(ggp.test)
mytext <- paste(test.dat$xmin,test.dat$ymin,sep = "")
style(ply.test, text = mytext, hoverinfo = "text", traces = c(1,2))

它产生了这个:

enter image description here