【问题标题】:Change size of hover text in Plotly在 Plotly 中更改悬停文本的大小
【发布时间】:2016-10-30 19:28:10
【问题描述】:

我正在基于 R 中的 ggplot 构建一个 Plotly 图。我想增加悬停框中文本的大小。假设我有一个这样的散点图:

library(plotly)
library(ggplot2)

d <- data.frame(a = sample(1:50, 30, T), 
                b = sample(1:50, 30, T), 
                col = factor(sample(1:3, 30, T)))

gg <- ggplot() + geom_point(aes(x = a, y = b, color = col), data = d)

p <– plotly_build(gg)
p

有没有办法改变悬停文本的大小?

【问题讨论】:

  • 请在下面查看我的答案,了解我认为在 R 中完成此任务的正确方法

标签: r plotly htmlwidgets


【解决方案1】:

目前似乎没有内置方法可以直接通过 plotly 传递附加属性来定义悬停外观(请参阅github issue #102)。但是,在问题描述中,您会看到用于悬停文本的类的名称,即.hovertext。最简单的解决方案是将您保存为 HTML 文件,然后在 HTML 的 &lt;head&gt; 部分的某处手动添加下面的 CSS。如果您还想更改图例文本的大小,请保留 .legendtext 行,如果不删除它们。

<style type="text/css">
.hovertext text {
    font-size: 100px !important;
}
.legendtext {
    font-size: 30px !important;
}
</style>

如果您想使用 R 注入 CSS 而不是手动注入,您有多种选择。

# the CSS we want to inject
css <- '
<style type="text/css">
.hovertext text {
    font-size: 100px !important;
}
.legendtext {
    font-size: 30px !important;
}
</style>'

library(plotly)
library(htmltools)
library(htmlwidgets)

1:创建后修改HTML文件

x <- as.widget(p)                                 # convert to htmlwidget object 
saveWidget(x, file="test_edited_1.html")          # and save to file
l <- readLines("test_edited_1.html")              # read file
h <- paste(l, collapse= " ")               
hh <- strsplit(h, "<head>")[[1]]                  # split where head appears
h.new <- paste(hh[1], css, hh[-1], collapse=" ")  # insert CSS
writeLines(h.new, "test_edited_1.html")           # write back to file

2:修改创建HTML文件的对象

x <- as.widget(p)                                 # convert to htmlwidget object 
# add a the code directly into <head> using `htmltools::htmlDependency`
x$dependencies <- list(
    htmlDependency(
        name = "custom",
        version="1",
        src="",
        head=css)  
    )
saveWidget(x, file="test_edited_2.html")

虽然第二个有效,但我不确定它是否正确使用 htmlDependency

结果

【讨论】:

    【解决方案2】:

    最近有一个update 可以让您更改悬停文本的各种特征。这是 R 中的一个示例:

    plot_ly(x=c(1:42),
            y=c(1:42),
            text=c(1:42),
          type="bar")%>%
      layout(
        title = paste("Top 42"),
        hoverlabel = list(font=list(size=10))
      )
    

    还有更改字体颜色、bgcolor 等的选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多