showtext icon indicating copy to clipboard operation
showtext copied to clipboard

plotly support

Open cttnguyen opened this issue 1 year ago • 0 comments

Could showtext provide some simple way to use custom fonts in plotly (without use of ggplotly())?

I had to use the following work around to use a custom font:

library(dplyr)
library(plotly)
library(showtext)

font_add_google("Gochi Hand", "gochi") #a script font
showtext_auto()

df <- data.frame(x = c(1,2,3), y = c(2,3,4))

p1 <- plot_ly(
    df,
    type = "scatter",
    mode = "lines",
    x = ~x,
    y = ~y
) %>% 
    layout(
        xaxis = list(title = list(text = "Date")), 
        yaxis = list(title = list(text = "Y Data")), 
        font = list(family = "gochi") #this alone doesn't work
    )

#get the source url to the font file from google
gochi_file <- showtextdb::google_fonts("Gochi Hand")$regular_url 

#create custom CSS 
gochi_css <- paste0(
  "<style type = 'text/css'>",
    "@font-face { ",
      "font-family: 'gochi'; ", #however you want to refer to it
      "src: url('", gochi_file, "'); ", #file from google
    "}",
  "</style>")

#add the CSS as a dependency for the plotly object
p2 <- p1
p2$dependencies <- c(
  p2$dependencies,
  list(
    htmltools::htmlDependency(
      name = "gochi-font", #these  first 3 arguments don't really matter for this use case
      version = "0",  
      src = "",
      head = gochi_css #refer to the custom CSS created
    )
  )
)

p1 %>% layout(title = list(text = "Not Gochi"))
p2 %>% layout(title = list(text = "Gochi"))

image image

cttnguyen avatar Dec 07 '22 16:12 cttnguyen