Change size of hover text in Plotly

房东的猫 提交于 2019-12-04 04:32:48

Currently there seems to be no built-in way to pass additional attributes to define the hover appearance directly via plotly (see github issue #102). However, in the issue description you see the name of the class used for the hover text, which is .hovertext. The simplest solution would be to save you plotly as an HTML file and add the CSS below by hand somewhere in the <head> part of the HTML. In case you want to change the size of the legend text as well, keep the .legendtext lines, if not erase them.

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

If you want to inject the CSS using R instead of doing it by hand you have several options.

# 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: modify the HTML file after creation

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: modify the object from which the HTML file is created

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

While the second works, I am not sure if it is a proper use of htmlDependency.

Result

There has been an update to plotly recently that allows you to change various characteristics of the hover text. Here's an example in 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))
  )

There are also options to change font color, bgcolor, and more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!