有没有办法在ggplotly中更改标签名称

时间:2019-10-12 09:23:19

标签: r ggplot2

我在解决以下问题方面遇到了挑战。请这里的专家帮助我。在我放置适当的代表之前,让我在这里解释问题:

df
   sd   x      y        x1         y1
1  1    12    1019    0.3867382  1.3484106
2  2    20    1016    1.7618076  0.8860984
3  3    7     1006   -0.4726801 -0.6549423
4  4    3     1009   -1.1602147 -0.1926301

好吧,我必须绘制x和y,但是它们的比例不同。所以我要做的是标准化数据并提出x1和y1。归一化公式为 ((x - mean(x)) / sd(x)

现在我需要绘制x1y1。所以做了一些数据争论,下面是它的代表。我正在获取输出,但是这里的主要问题是,由于x1y1被绘制,当我将光标移到它上面时,它们显示x1y1的值,我不想要的。即使绘制了x1y1,我仍需要显示实际值(xy值)。有没有办法做到这一点?

library(ggplot2)
library(plotly)
require(reshape)
df <- structure(list(sd = c(1, 2, 3, 4), x = c(12, 20, 7, 3), 
                     y = c(1019, 1016, 1006, 1009), 
                     x1 = c(0.386738249968166, 1.76180758318831, -0.472680083294425, -1.1602147499045), 
                     y1 = c(1.34841060188091, 0.886098395521742, -0.654942292342157, -0.192630085982987)), 
                row.names = c(NA, -4L), class = "data.frame")   

df$x <- NULL
df$y <- NULL
df1 <- melt(df,id=c("sd"))
ggplotly(ggplot(data = df1, aes(x = sd, y = value, color = variable))
          + geom_line(size=0.2))

1 个答案:

答案 0 :(得分:2)

可能有很多方法,但是在格式化数据框之后,您可以使用tooltip="text"在此处显示所需的工具提示。

df1 <- df  
df1$x <- NULL
df1$y <- NULL
dfx <- melt(df1,id=c("sd"))


df2 <- df  
df2$x1 <- NULL
df2$y1 <- NULL
dfy <- melt(df2,id=c("sd"))
names(dfy) <- c("sd1", "variable1", "value1")

df <- cbind(dfx,dfy)

ggplotly(ggplot(data = df,aes(x=sd, y=value, color=variable, text=value1))+
           geom_line(size=0.2), tooltip = "text")