在Plotly中更改悬停文本的大小 [英] Change size of hover text in Plotly

查看:298
本文介绍了在Plotly中更改悬停文本的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a Plotly plot based on a ggplot in R. I would like to increase the size of the text in the hover boxes. Suppose I have a scatterplot like this:

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

是否可以更改悬停文字的大小?

Is there a way to change the size of the hover text?

推荐答案

当前似乎没有内置的方法可以直接通过plotly传递其他属性来定义悬停外观(请参见

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>

如果您想使用R而不是手工进行CSS注入,则有多种选择.

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:创建后修改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.

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

这篇关于在Plotly中更改悬停文本的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆