【问题标题】:Can text labels and hover text be used in plotly?可以在情节中使用文本标签和悬停文本吗?
【发布时间】:2017-02-20 06:09:07
【问题描述】:

我希望在一个有情节的交互式图形中将文本作为标签,并将鼠标悬停在这些标签上以获取更多信息。

但是,plotly 不允许我在同一行代码中使用文本标签和悬停文本。我非常关注文本标签,不想使用简单的散点。

有没有办法修复下面的代码,以便显示文本标签和悬停文本?

谢谢。

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

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    您可以执行类似于here 建议的解决方案的操作,即仅为悬停文本创建散点图并将文本添加为​​注释。

    请参阅下面的 sn-p。

    # 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
    

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 1970-01-01
      • 2011-11-16
      • 2021-04-02
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多