在 ggplot 标题中使用 HTML 元素

Ant*_*ino 3 html r ggplot2 shiny

提前感谢支持这个问题。我正在开发一个 Shiny 应用程序,其中包含一些有关向州检察长办公室提交的投诉的数据。我将制作交互式 ggplot 图形和其他东西。我想用 HTML 元素为我的 ggplot 的标题赋予样式(我不知道在我试图用那个标题做的复杂级别上有任何其他方法来做到这一点)。由于我的数据的性质以及我使用的 csv 和 Rdata 文档的数量,我无法提供可重复的示例,对此我深表歉意。

下面的代码代表了 ggplot 部分以及我如何在 renderPlot 环境中引入它。如果有人能告诉我如何在 ggplot 的标题中使用 HTML 元素,或者有任何其他选项可以在句子和粗体文本之间引入空格(不是所有文本,只是几个字),我将不胜感激。

library(extrafont)
loadfonts(device = "win")
library(openxlsx)
library(zoo)
library(ggplot2)
library(gridExtra)
library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(shinyjqui)
library(shinyjs)
library(plyr)
library(dplyr)
library(dbplyr)
library(dint)
library(bbplot)
library(osmdata)
library(stats)

  graph_1 <- reactiveValues()
  observeEvent({
    input$tentativa
    input$provincia
    input$periodo_tipo
    input$periodo_ranking
    input$periodo_ranking_t
    input$periodo_ranking_m
  },{


      datos<-datos_f()
      datos<-datos %>% count(datos$delitos)
      datos<-datos %>% 
        rename(
          delitos = `datos$delitos`,
        )
      datos<-join(x = datos, y =catalogo_delito,
                  by = "delitos"  )
      datos$Tipo_Delito_PJ<- NULL
      #eliminar duplicados
      datos<-datos[!duplicated(datos$delitos), ]

      datos<-datos[order(datos$n, na.last = TRUE, decreasing = TRUE),]
      datos$n_total<-sum(datos$n)
      datos$porcent<-(datos$n / datos$n_total)*100
      datos$cumfreq<-cumsum(datos$porcent)
      datos<-filter(datos, cumfreq<81)
      datos<-datos[order(datos$porcent, na.last = TRUE, decreasing = TRUE),]
      datos$porcent<-format(round(datos$porcent, 2), nsmall = 2)
      datos$porcent<-as.numeric(datos$porcent)
      datos$cumfreq<-NULL
      datos$n_total<-NULL

      NROF =nrow(datos)
      if(NROF !=0)
      {

        if (req(input$periodo_tipo)== "Anual") {
          titulo <- paste0("Delitos que representan el 80%  de las denuncias a nivel ", input$provincia, " en ",input$periodo_ranking, " (Valores en porcentajes)")
          # paste0("       Delitos que representan el 80%  de las denuncias\n",
          #        "                             a nivel ", input$provincia, " en ",input$periodo_ranking, " (Valores en porcentajes)")
        }else if (req(input$periodo_tipo)== "Trimestral"){
          titulo <- paste0("Delitos que representan el 80%  de las denuncias a nivel ", input$provincia, " en ",input$periodo_ranking_t, " (Valores en porcentajes)")
          # paste0("       Delitos que representan el 80%  de las denuncias\n",
          #        "                             a nivel ", input$provincia, " en ",input$periodo_ranking_t, " (Valores en porcentajes)")
        }else if (req(input$periodo_tipo)== "Mensual"){
          titulo <- paste0("Delitos que representan el 80%  de las denuncias a nivel ", input$provincia, " en ",input$periodo_ranking_m, " (Valores en porcentajes)")
          # paste0("       Delitos que representan el 80%  de las denuncias\n",
          #      "                             a nivel ", input$provincia, " en ",input$periodo_ranking_m, " (Valores en porcentajes)")

a<-1.02*as.numeric(max(datos$porcent))      
bars <- ggplot(datos, aes(x = reorder(Abreviaciones,-porcent), y = porcent,
                                  sprintf("%0.2f", round(porcent, digits = 2)))) +
          geom_bar(stat="identity", 
                   position="identity", 
                   fill="#1380A1", cex=0.5) +
          bbc_style()+
          theme(plot.title = element_text(size = 20, hjust = 0.5)) +
          ggtitle(wrapper(titulo, 70, 0.0)) +
          geom_text(aes(label=porcent), vjust=-0.18, color="black", size=4.5, fontface = "italic")+
          theme(axis.text.x =element_text(angle=45, hjust=1, vjust=1.15, 
                                                    size=14),
                axis.text.y=element_text(size=13.5),
                plot.caption = element_text(hjust = 1, margin = margin(-10,0,0,-20), size = 12))+
          ylim(0,a)

bars <- bars + labs(caption = htmlhtmltools::tags$caption(paste0(strong("Fuente:")," Sistema de actuaciones fiscales (SIAF)",br(),strong("Elaboración:")," Dirección de Estadística y Sistemas de Información)",br(),strong("Nota:"),br(),p(" Los datos del año 2014 representan a las denuncias registradas a partir del Código Orgánico Integral Penal (Agosto-2014).","Los datos del año ",wrapper(vfecha_anio[length(vfecha_anio)],6,2.0)," representan a las denuncias registradas hasta ",wrapper(tolower(as.character(abrev_mes$nombre[abrev_mes$mes_completo == unique(as.character(substring(reportesFGE2$mes[as.numeric(reportesFGE2$id_mes)==max(as.numeric(reportesFGE2$id_mes))],6,8)))])),6,2.0),"."))) 

#The labs code is what I want to use. I want to introduce html elements to the text of the caption option.
#A possible answer could be using bold text with bold() (I use strong() because it is the bold 
#version of HTML elements), but I don't want the whole expression to be a single sentence. 
#I want to give some space between certain sentences (br() introduce space between to sentences)
#Or maybe introducing another element instead of caption, like annotate, but it is imperative not to
#be obligated to put x and y coordinates because it distorts the image.



        graph_1$plot1<-bars

      } else {
        plot(0,0,type="n", xlab = "", ylab = "")
        text(0,0,"", font=2, cex=1.5)
      }

    })

  # Gráficos 1era pestaña, renderPlot#### 
  output$plot1<-renderPlot({

    ##
    withProgress(message = 'Calculation in progress',
                 detail = 'This may take a while...', value = 0, {
                   for (i in 1:15) {
                     incProgress(1/15)
                     Sys.sleep(0.05)
                   }
                 })
    ##

    graph_1$plot1

  })
Run Code Online (Sandbox Code Playgroud)

bsc*_*idr 5

ggtextClaus Wilke令人难以置信的包(目前可在GithubCRAN上使用)允许您在使用ggplot2.

这是一个从包的文档中稍微改编的示例。请注意,在labs(caption = ...)代码中,我混合使用了 HTML 代码(用于加粗)和 Markdown(用于斜体)。

library(ggplot2)
library(ggtext)

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point(size = 3) +
  scale_color_manual(
    name = NULL,
    values = c(setosa = "#0072B2", virginica = "#009E73", versicolor = "#D55E00"),
    labels = c(
      setosa = "<i style='color:#0072B2'>I. setosa</i>",
      virginica = "<i style='color:#009E73'>I. virginica</i>",
      versicolor = "<i style='color:#D55E00'>I. versicolor</i>")
  ) +
  labs(
    title = "**Fisher's *Iris* dataset**  
    <span style='font-size:11pt'>Sepal width vs. sepal length for three *Iris*
    species</span>",
    x = "Sepal length (cm)", y = "Sepal width (cm)",
    caption = "<b>Source</b>: *Fisher's Iris dataset*"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_markdown(lineheight = 1.1),
    legend.text = element_markdown(size = 11),
    plot.caption = element_markdown(size = 11)
  )
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明