为什么在使用 ggplotly 时我的工具提示的顺序会改变?

时间:2021-04-29 22:24:29

标签: r ggplot2 plotly ggplotly

当我将自己的文本添加到 ggplotly 的工具提示中时,文本的顺序会发生变化。在我的示例中,我的文本中的顺序是葡萄牙语然后是德语,但是在情节上顺序是不同的。

我该如何解决这个问题?

谢谢

library(ggplot2);
library(plotly);

language <- c("de","es","hi","pt","sv","en")
averageRating <- c(6,4,3,9,10,30)
my_data <- data.frame(language, averageRating)
text <- c("Portuegese","German","Spanish","Hindi","Swedish","English")
p <- ggplot(data=my_data, aes(x=language, y=averageRating, text = text)) +
geom_bar(stat = "identity")

ggplotly(p, tooltip = c("text"))

2 个答案:

答案 0 :(得分:0)

也许你应该在应用factor时在aes内尝试ggplot,例如,

ggplot(data = my_data, aes(x = factor(language, levels = language), y = averageRating, text = text))

答案 1 :(得分:0)

为了解决这个问题,我在数据框中添加了一个新列,名称是我希望在工具提示中显示的名称。然后我将美学中的“文本”设置为该列名称。

library(ggplot2);
library(plotly);
my_data <- read.csv("languageVsRating.csv")
p <- ggplot(data=my_data, aes(x=reorder(language,-averageRating), y=averageRating, text = fullName)) +
geom_bar(stat = "identity") +
labs(x="Film Language",y="Average Rating")+
geom_hline(aes(yintercept = 6.9,linetype="Mean"),colour='red',size=1)+
geom_hline(aes(yintercept = 6.7,linetype="Median"),colour='blue',size=1)+
scale_linetype_manual(name = "",values = c(2,2),guide = guide_legend(override.aes = list(color = c("red", "blue"))))

ggplotly(p, tooltip = c("text","y"))

languageVsRating.csv 中还有一列是语言全名