簡體   English   中英

在Plotly中更改懸停文本的大小

[英]Change size of hover text in Plotly

我正在根據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

有沒有辦法改變懸停文本的大小?

目前似乎沒有內置的方法來傳遞額外的屬性來直接通過plotly定義懸停外觀(參見github問題#102 )。 但是,在問題描述中,您會看到用於懸停文本的類的名稱,即.hovertext 最簡單的解決方案是將您作為HTML文件保存,並在HTML的<head>部分手動添加下面的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

結果

在此輸入圖像描述

最近有一個更新 ,允許您更改懸停文本的各種特征。 這是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等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM