Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

plotly support #63

Open
cttnguyen opened this issue Dec 7, 2022 · 0 comments
Open

plotly support #63

cttnguyen opened this issue Dec 7, 2022 · 0 comments

Comments

@cttnguyen
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant