es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Obtén que R muestre e imprima el signo mayor o igual, el signo menor o igual, y el exponente utilizando ggplot.

Tengo las estimaciones y los correspondientes intervalos de confianza del 95% de un modelo de regresión que estoy intentando graficar.

Los datos se ven así:

library(tidyverse)

mydata <- structure(list(term = structure(c(1L, 7L, 18L, 19L, 20L), .Label = c("Edad (años)", 
"Sexo (hombre)", "Nunca fumador (referencia)", "Fumador actual", "Exfumador", 
"Obesidad", "IMC (kg/m^2)", "Diabetes", "Glucosa (mmol/L)", "Uso de medicamentos para la reducción de la glucosa",
"Hipertensión", "Presión arterial sistólica (mmHg)", "Presión arterial diastólica (mmHg)", 
"Uso de medicamentos antihipertensivos", "Hipercolesterolemia", "Colesterol LDL (mmol/L)", 
"Uso de medicamentos para la reducción de lípidos", ">90 (referencia)", "60-89", 
"<60"), class = c("ordered", "factor")), estimate = c(0.4, 0.9, 
1, 1.5, 1.9), conf_low = c(0.2, 1.4, 0.95, 1, 1.7), conf_high = c(0.6, 
0.6, 1.05, 2, 2.1)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

mydata
<h1>A tibble: 5 x 4</h1>

<p>term            estimate conf_low conf_high
  <ord>              <dbl>    <dbl>     <dbl>
1 Edad (años)          0.4     0.2       0.6 
2 IMC (kg/m^2)         0.9     1.4       0.6 
3 >90 (referencia)      1       0.95      1.05
4 60-89                1.5     1         2<br>
5 <60                  1.9     1.7       2.1

He plotado estos números de la siguiente manera:

ggplot(data=mydata,
aes(x=estimate, y=fct_rev(term))) +
geom_point() +
geom_errorbarh(aes(xmin=conf_low, xmax=conf_high, height=0.15)) +
annotation_custom(grob=grid::textGrob(label="Enfermedad renal crónica",
gp=grid::gpar(fontface="bold", fontsize=11),
hjust=1.0),
xmin=-Inf, xmax=-Inf, ymin=3.2, ymax=3.2) +
coord_cartesian(clip="off") +
#scale_x_continuous(expand=expansion(mult=c(.05, .3))) +
theme(axis.text.y=element_text(margin=margin(t=0, r=2.2, b=0, l=40, "pt"))) +
scale_y_discrete(name="")

enter image description here

Me gustaría lograr las siguientes cosas que no puedo hacer que funcionen:

  1. En la etiqueta de IMC en el eje Y, el ^2 debe ser sobrescrito. He intentado expression(), pero eso no parece funcionar.

  2. En la etiqueta de la variable Enfermedad Renal Crónica en el eje Y, el >90 debe ser un signo de ‘mayor o igual que’, y el <60 un signo de 'menor o igual que'. Aquí he intentado la expresión y los códigos unicode, pero ambos no parecen funcionar.

Editar
Añado información de sesión ya que esto puede ser útil:
“`
library(utils)
sessionInfo(package=NULL)

R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
<a href="https://i.stack.imgur.com/l8yS8.png">1</a> LC_COLLATE=Dutch_Netherlands.1252 LC_CTYPE=Dutch_Netherlands.1252 LC_MONETARY=Dutch_Netherlands.1252
[4] LC_NUMERIC=C LC_TIME=Dutch_Netherlands.1252

attached base packages:
<a href="https://i.stack.imgur.com/l8yS8.png">1</a> stats graphics grDevices utils datasets methods base

other attached packages:
<a href="https://i.stack.imgur.com/l8yS8.png">1</a> forcats_0.5.1 stringr_1.4.0 dplyr_1.0.7 purrr_0.3.4 readr_2.1.0 tidyr_1.1.4 tibble_3.1.6
[8] ggplot2_3.3.5 tidyverse_1.3.1

loaded via a namespace (and not attached):
<a href="https://i.stack.imgur.com/l8yS8.png">1</a> Rcpp_1.0.7 cellranger_1.1.0 pillar_1.6.4 compiler_4.1.2 dbplyr_2.1.1 tools_4.1.2<br>
[7] digest_0.6.28 jsonlite_1.7.2 lubridate_1.8.0 lifecycle_1.0.1 gtable_0.3.0 pkgconfig_2.0.3
[13] rlang_0.4.12 reprex_2.0.1 cli_3.1.0 rstudioapi_0.13 DBI_1.1.1 haven_2.4.3<br>
[19] xml2_1.3.2 withr_2.4.2 httr_1.4.2 fs_1.5.0 generics_0.1.1 vctrs_0.3.8<br>
[25] hms_1.1.1 grid_4.1.2 tidyselect_1.1.1 glue_1.5.0 R6_2.5.1 fansi_0.5.0<br>
[31] readxl_1.3.1 farver_2.1.0 tzdb_0.2.0 modelr_0.1.8 magrittr_2.0.1 backports_1.3.0
[37] scales_1.1.1 ellipsis_0.3.2 rvest_1.0.2 assertthat_0.2.1 colorspace_2.0-2 labeling_0.4.2<br>
[43] utf8_1.2.2 stringi_1.7.5 munsell_0.5.0 broom_0.7.10 crayon_1.4.2

“`

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para lograr la formato requerido para los superíndices y caracteres especiales, puedes utilizar los caracteres Unicode directamente dentro de la columna ‘term’ del conjunto de datos. Por ejemplo, para representar el carácter de superíndice 2 en “BMI (kg/m^2)”, puedes utilizar el carácter Unicode U+00B2 (²) de la siguiente manera:

    mydata$term[2] <- "BMI (kg/m²)"
    

    De manera similar, para representar los signos “menor o igual que” y “mayor o igual que”, puedes utilizar los caracteres Unicode U+2264 () y U+2265 (), respectivamente:

    mydata$term[3] <- "≥90 (referencia)"
    mydata$term[5] <- "≤60"
    

    Ahora, cuando grafiques los datos utilizando ggplot, la formatación requerida se mostrará automáticamente:

    ggplot(data=mydata,
           aes(x=estimate, y=fct_rev(term))) +
      geom_point() +
      geom_errorbarh(aes(xmin=conf_low, xmax=conf_high, height=0.15)) +
      annotation_custom(grob=grid::textGrob(label="Enfermedad renal crónica", 
                                            gp=grid::gpar(fontface="bold", fontsize=11), 
                                            hjust=1.0), 
                        xmin=-Inf, xmax=-Inf, ymin=3.2, ymax=3.2) + 
      coord_cartesian(clip="off") + 
      #scale_x_continuous(expand=expansion(mult=c(.05, .3))) +
      theme(axis.text.y=element_text(margin=margin(t=0, r=2.2, b=0, l=40, "pt"))) +
      scale_y_discrete(name="")
    

    Esto producirá el siguiente gráfico:

    Gráfico con superíndices y caracteres especiales

Comments are closed.