2017-02-20 51 views
2

我希望將文本作爲標籤以圖表形式交互式顯示,並將鼠標懸停在這些標籤上以獲取更多信息。文字標籤和懸停文字可以用於陰謀嗎?

但是,情節不會讓我有文本標籤和懸停在同一行代碼中的文本。我拼命地在文本標籤之後,不希望使用簡單的分散點。

有沒有一種方法可以修復下面的代碼,以便文本標籤可以呈現並懸停文本?

感謝。

# 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)) 

回答

4

你可以做類似的解決方案建議的東西here,即創建一個散點圖只是爲hovertext並添加文本註釋。

enter image description here

請參見下面的代碼片段。

# 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