我希望在图形交互图中将文字作为标签,并将鼠标悬停在这些标签上以获取更多信息。
然而,情节上不会让我在同一行代码中有文本标签和悬停文本。我拼命地在文本标签之后并且不希望使用简单的散点。
有没有办法可以修改下面的代码,以便显示文字标签并悬停文字?
感谢。
# Load packages
require(ggplot2)
require(plotly)
# Example data
data(iris)
str(iris)
# Create new columns - with more information
iris$Symbol <- c("Se", "Ve", "Vi")[iris$Species]
iris$PlantedBy <- c("Bruce", "Joe", "Eliza")[iris$Species]
# Create in ggplot
ggplot(iris, aes(x = Sepal.Length, y =Sepal.Width, colour = Species,
label = Symbol)) +
geom_text(fontface = "bold", size = 6) +
theme_classic() +
theme(legend.position = "none")
# Plotly - point with hover text
plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter',
mode = 'text',
text = ~Symbol)
# Plotly - point with hover text (does not work)
plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter',
mode = 'text',
text = ~Symbol,
hoverinfo = 'text',
text = ~paste('Species: ', Species,
'</br> Planted by: ', PlantedBy))
答案 0 :(得分:4)
您可以执行与建议的here解决方案类似的操作,即仅为hovertext创建散点图并将文本添加为注释。
请参阅下面的代码段。
# Load packages
require(plotly)
# Example data
data(iris)
# Create new columns - with more information
iris$Symbol <- c("Se", "Ve", "Vi")[iris$Species]
iris$PlantedBy <- c("Bruce", "Joe", "Eliza")[iris$Species]
# Create scatter plot with no markers but hovertext
p <- plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width,
type = 'scatter',
mode = 'markers',
hoverinfo = 'text',
text = ~paste('Species: ', Species,
'</br> Planted by: ', PlantedBy),
marker = list(size=1)) %>%
#add annotations for text symbols
add_annotations(
x= iris$Sepal.Length,
y = iris$Sepal.Width,
text = iris$Symbol,
showarrow = F,
xref = "x",
yref = "y"
)
p