在ggplot标题中使用HTML元素

在ggplot标题中使用HTML元素,html,r,ggplot2,shiny,Html,R,Ggplot2,Shiny,提前感谢您对这个问题的支持。我正在开发一个闪亮的应用程序,其中包含一些关于向州检察长办公室提交投诉的数据。我将制作交互式ggplot图形和其他东西。我想用HTML元素为我的ggplot的标题赋予风格(我不知道在复杂程度上如何处理标题)。由于我的数据的性质以及我使用的csv和Rdata文档的数量,我无法提供一个可复制的示例,对此我深表歉意 下面的代码表示ggplot部分以及我如何在renderPlot环境中引入它。如果有人能告诉我如何在ggplot的标题中使用HTML元素,或者有任何其他选项在句子

提前感谢您对这个问题的支持。我正在开发一个闪亮的应用程序,其中包含一些关于向州检察长办公室提交投诉的数据。我将制作交互式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

  })
库(extrafont)
loadfonts(device=“win”)
库(openxlsx)
图书馆(动物园)
图书馆(GG2)
图书馆(gridExtra)
图书馆(闪亮)
图书馆(shinyWidgets)
图书馆(shinydashboard)
图书馆(shinyjqui)
图书馆(shinyjs)
图书馆(plyr)
图书馆(dplyr)
图书馆(dbplyr)
图书馆(力)
图书馆(bbplot)
图书馆(osmdata)
图书馆(统计)

graph_1克劳斯·威尔克(Claus Wilke)的不可思议的
ggtext
软件包(目前在和上提供)允许您在使用
ggplot2
创建的绘图的文本元素中使用标记或CSS/HTML代码

下面是一个从包的文档中稍加修改的示例。请注意,在
实验室(caption=…)
代码中,我混合使用了HTML代码(用于粗体)和标记(用于斜体)

库(ggplot2)
图书馆(ggtext)
ggplot(鸢尾,aes(萼片长度,萼片宽度,颜色=种))+
几何点(尺寸=3)+
比例\颜色\手册(
name=NULL,
值=c(setosa=“#0072B2”,virginica=“#009E73”,versicolor=“#D55E00”),
标签=c(
setosa=“I.setosa”,
virginica=“I.virginica”,
versicolor=“I.versicolor”)
) +
实验室(
title=“**Fisher's*虹膜*数据集**
三个*虹膜的萼片宽度与萼片长度*
物种“,
x=“萼片长度(厘米)”,y=“萼片宽度(厘米)”,
说明=“来源:*费舍尔虹膜数据集*”
) +
主题_极小值()+
主题(
plot.title=元素标记(线宽=1.1),
legend.text=元素\标记(大小=11),
plot.caption=元素\标记(大小=11)
)

请参阅,举一个简单的例子,是否可以仅使用基于iris数据的简单绘图?似乎因为这个闪亮的代码本质上只是创建绘图的图像文件,所以没有必要在示例中包含所有闪亮的代码。哦,我喜欢这个社区!,非常感谢您对@bschneidr的支持
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)
  )