[英]Change size of hover text in 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. 我正在根据R中的ggplot构建一个Plotly图。我想增加悬停框中文本的大小。 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? 有没有办法改变悬停文本的大小?
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 ). 目前似乎没有内置的方法来传递额外的属性来直接通过plotly定义悬停外观(参见github问题#102 )。 However, in the issue description you see the name of the class used for the hover text, which is
.hovertext
. 但是,在问题描述中,您会看到用于悬停文本的类的名称,即
.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. 最简单的解决方案是将您作为HTML文件保存,并在HTML的
<head>
部分手动添加下面的CSS。 In case you want to change the size of the legend text as well, keep the .legendtext
lines, if not erase them. 如果您想要更改图例文本的大小,请保留
.legendtext
行,如果不删除它们。
<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. 如果你想用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)
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
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
. 虽然第二个工作,我不确定它是否正确使用
htmlDependency
。
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:
这是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. 还可以选择更改字体颜色,bgcolor等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.