2016-06-28 70 views
5

我正在根據R中的ggplot構建一個Plotly圖。我想要增加懸停框中文本的大小。假設我有這樣一個散點圖:在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 

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

+0

請參閱下面的答案,我相信是在R中完成此操作的正確方法 – rmg

回答

4

目前似乎沒有內置的方式來通過附加屬性直接通過繪製來定義懸停外觀(請參閱github issue #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

結果

enter image description here

1

已經有一個update到plotly最近,允許您更改懸停文本的各種特性。下面是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等的選項。