Plotly and Highchart
Plotly
Time Series
Caso I: Univariate
GYY <- ggplot(GY, aes(x=Fecha, y=Activos)) +
geom_line(size=1, colour="darkblue")+theme_economist()+
theme(legend.position = 'none',
legend.direction = 'horizontal',
legend.title = element_blank()) + ylab('En millones USD')## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## i Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
Caso II: Multi-variate
| Japón | Korea | Fecha |
|---|---|---|
| 242.45 | 310.74 | 2026-02-01 |
| 293.01 | 326.01 | 2023-01-01 |
| 266.98 | 295.78 | 2025-11-01 |
| 294.96 | 295.75 | 2029-01-01 |
| 292.35 | 318.34 | 2027-04-01 |
| 289.41 | 319.14 | 2023-10-01 |
| 242.45 | 310.74 | 2030-04-01 |
| 292.72 | 310.30 | 2023-06-01 |
Con esta rutina transformamos la base en formato long.
| Fecha | Países | Exportaciones |
|---|---|---|
| 2028-09-01 | Japón | 269.64 |
| 2026-06-01 | Japón | 276.36 |
| 2026-08-01 | Korea | 310.53 |
| 2024-08-01 | Japón | 266.13 |
| 2029-11-01 | Korea | 282.08 |
| 2027-10-01 | Korea | 320.71 |
| 2030-01-01 | Japón | 266.98 |
| 2028-11-01 | Korea | 289.98 |
p <- ggplot(data=data_II,
aes(x=Fecha, y=Exportaciones, colour=Países)) +
geom_line()+scale_color_manual(values = c("#0b5394", "firebrick4"))+
theme(legend.position = 'bottom',
legend.title = element_blank(),
axis.line = element_line(size=1, colour = "black"),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
text = element_text(family="mono"),
axis.text.x = element_text(colour="black", size = 14),
axis.text.y = element_text(colour="black", size = 14),
axis.title = element_text(size = 15))+
scale_y_continuous(labels=dollar_format(prefix="$",suffix=" M"))## Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
## i Please use the `linewidth` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
Highcharter
Para mayor información : https://jkunst.com/highcharter/, https://byollin.github.io/RInteractiveCharts/#29
Histograma
Time Series
Caso I
| Fecha | Países | Importaciones |
|---|---|---|
| 2022-01-01 | Ecuador | 250.00 |
| 2022-02-01 | Ecuador | 231.64 |
| 2022-03-01 | Ecuador | 249.05 |
| 2022-04-01 | Ecuador | 252.00 |
| 2029-12-01 | Italia | 257.93 |
| 2030-01-01 | Italia | 264.26 |
| 2030-02-01 | Italia | 259.55 |
| 2030-03-01 | Italia | 260.62 |
| 2030-04-01 | Italia | 254.68 |
Caso II: Cambio de colores y tipo de línea
# https://jkunst.com/blog/posts/2020-05-22-30diasdegraficos-parte-2/
#http://jkunst.com/LatinR-2019-Highcharter-taller/slides/#6
#http://jkunst.com/LatinR-2019-Highcharter-taller/slides/#3
Tipo_colores <- c("#203764", "#548235")
Tipo_linea <- c("Solid", "ShortDashDotDot")
H1 <- hchart(Mundial, type = "line", hcaes(x = Fecha, y = Importaciones, group = Países),
color = Tipo_colores,dashStyle = Tipo_linea)%>%
hc_title(text = "Importaciones Ecuador vs Italia")
H1Caso III: Theme economist
# https://jkunst.com/blog/posts/2020-05-22-30diasdegraficos-parte-2/
#http://jkunst.com/LatinR-2019-Highcharter-taller/slides/#6
#http://jkunst.com/LatinR-2019-Highcharter-taller/slides/#3
#https://jkunst.com/blog/posts/2020-05-22-30diasdegraficos-parte-2/
H3 <- hchart(Mundial, type = "line", hcaes(x = Fecha, y = Importaciones,
group = Países))%>%
hc_title(text = "Importaciones Ecuador vs Italia") %>%
hc_add_theme(hc_theme_economist())
H3Caso IV: library:forecast
library(forecast)
library(sweep)
library(timetk)
Mundial_EC <- Mundial %>% dplyr::filter(Países== "Ecuador")
BA_ts <- tk_ts(Mundial_EC, start = 2022, freq = 12, silent = TRUE)
pronosticos <- forecast(auto.arima(BA_ts), h = 6, level = 95)
H4 <- hchart(pronosticos) %>%
hc_title(
text = "Pronóstico Importaciones aplicando libreria forecast"
) %>%
hc_tooltip(shared = TRUE, valueDecimals = 2)
H4Caso V: Two time series.
| Fecha | Cobra | Python |
|---|---|---|
| 2022-01-01 | 1250.00 | 1300.00 |
| 2022-02-01 | 1241.50 | 1307.16 |
| 2022-03-01 | 1253.04 | 1298.07 |
| 2022-04-01 | 1249.39 | 1296.92 |
| 2022-05-01 | 1264.72 | 1302.90 |
# First ensure your locale is set to Spanish
#Sys.setlocale("LC_TIME", "es_ES.UTF-8") # Linux/Mac
Sys.setlocale("LC_TIME", "Spanish") # Windows## [1] "Spanish_Spain.1252"
AD <- highchart() %>%
hc_xAxis(
categories = format(America$Fecha, "%b-%Y"), # Format dates directly
title = list(text = "Fecha"),
labels = list(style = list(fontSize = "10px"))
) %>%
hc_yAxis(
title = list(text = "Exportaciones", style = list(fontSize = "12px")),
gridLineWidth = 0
) %>%
hc_add_series(
name = "Cobra",
data = America$Cobra,
type = "line",
color = "#1E90FF"
) %>%
hc_add_series(
name = "Python",
data = America$Python,
type = "line",
color = "#990000"
) %>%
hc_title(text = "Evolución Mensual - 2022-2024") %>%
hc_tooltip(
shared = TRUE,
crosshairs = TRUE,
pointFormat = "<span style='color:{point.color}'>\u25CF</span> {series.name}: <b>{point.y}</b><br/>"
) %>%
hc_legend(align = "center", verticalAlign = "bottom")
ADBar Chart
Caso I
- Para cambiar el nombre del eje x, se debe aplicar la siguiente rutina:
hc_xAxis(title = list(text = “Fecha”))
- Para las etiquetas a las variables, se aplica lo siguiente:
dataLabels=list(enabled=TRUE, format=‘{point.Exportaciones}’))
load("D:/Documentos/Estadisticos/R/R_studio/Plotly/File_One.RData")
B1 <- hchart(jjj, type = 'column', hcaes(x = factor(fecha), y = Exportaciones,
group = Continente),
dataLabels=list(enabled=TRUE, format='{point.Exportaciones}')) %>%
hc_xAxis(
title = list(text = "Fecha")
)%>%
hc_add_theme(hc_theme_ft())
B1Caso II: Stacked bar
Caso II: Stacked bar- Opcion B
| Años | Cartera de créditos | Fondos Disponibles | Inversiones |
|---|---|---|---|
| 2016-12 | 57.85 | 25.01 | 17.15 |
| 2017-12 | 63.64 | 20.49 | 15.87 |
| 2018-12 | 67.47 | 18.37 | 14.16 |
| 2019-12 | 68.34 | 16.49 | 15.16 |
| 2020-12 | 60.85 | 22.89 | 16.26 |
Para este ejericio es importante mencionar, que se deben realizar modificaciones previas a la base de datos, de tal manera, que la suma de los tres componentes den el 100.
Si deseamos etiquetar las columnas, aplicamos la siguiente rutina:
hc_plotOptions(column = list(stacking = “normal”), series = list(boderWidth = 0, dataLabels = list(enabled = TRUE)))
La primera línea indica que nuestro gráfico tendrá columnas apiladas. La segunda y tercera línea indica, que queremos que estén fijas las leyendas en cada barra.
#https://blogs.sap.com/2019/09/19/top-bottom-analysis-using-r-visualizations-part-2/
#https://www.tmbish.me/lab/highcharter-cookbook/
highchart() %>%
hc_chart(type = "column") %>%
hc_plotOptions(column = list(stacking = "normal"),
series = list(boderWidth = 0,
dataLabels = list(enabled = TRUE))) %>%
hc_xAxis(categories = Blades_A$Años) %>%
hc_add_series(name="Inversiones",
data = Blades_A$Inversiones,
stack = "Activos")%>%
hc_add_series(name="Fondos Disponible",
data = Blades_A$`Fondos Disponibles`,
stack = "Activos") %>%
hc_add_series(name="Cartera de Créditos",
data = Blades_A$`Cartera de créditos`,
stack = "Activos")%>%
hc_yAxis(min=0,max=100)%>%
hc_add_theme(hc_theme_elementary())Caso III: Otro ejemplo
| Departamento | Masculino | Femenino |
|---|---|---|
| Dept A | 875 | 208 |
| Dept B | 610 | 125 |
| Dept C | 375 | 693 |
| Dept D | 467 | 475 |
| Dept E | 241 | 493 |
| Dept F | 423 | 441 |
seg1_name = "Masculino"
seg2_name = "Femenino"
color1 = "#830808"
color2 = "#0b467b"
title_caption = "Inscritos en la Facultad de Economía 2022"
highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = title_caption,
margin = 20, align = "center",
style = list(color = "black", fontWeight = "bold")) %>%
hc_plotOptions(column = list(stacking = "normal",
dataLabels = list(enabled = TRUE))) %>%
hc_legend(align = "left", layout = "vertical", verticalAlign = "top",
x=0, y= 250, symbolRadius = 0 ) %>%
hc_xAxis(categories = df$Departamento,
tickLength = 0, lineWidth = 3, lineColor = "black",
labels = list(style = list(fontSize = "14px", fontWeight = "bold"))) %>%
hc_yAxis(title = list(text = "Número de inscritos"),
stackLabels = list(color = "black", fontWeight = "bold", enabled = TRUE)) %>%
hc_tooltip(enabled = FALSE) %>%
hc_add_series(name=seg1_name, data = df$Masculino, color = color1) %>%
hc_add_series(name=seg2_name, data = df$Femenino, color = color2)Con Porcentajes
- Para que las etiquetas nos aparezcan con el signo de porcentajes, aplicamos la siguiente rutina
hc_plotOptions(column = list(stacking = “percent”, dataLabels = list(enabled = TRUE, format = “{percentage:,.1f}%”)))
- Para que el eje y aparezca signo de porcentajes, aplicamos la siguiente rutina
hc_yAxis(title = list(text = “Porcentajes de postulantes”), labels = list(format = “{value}%”))
title_caption = "Porcentajes de hombres vs mujeres"
seg1_name = "Masculino"
seg2_name = "Femenino"
color1 = "#830808"
color2 = "#0b467b"
highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = title_caption ,
margin = 20, align = "center",
style = list(color = "black", fontWeight = "bold")) %>%
hc_plotOptions(column = list(stacking = "percent",
dataLabels = list(enabled = TRUE, format = "{percentage:,.1f}%"))) %>%
hc_legend(align = "left", layout = "vertical", verticalAlign = "top",
x=0, y= 250, symbolRadius = 0 ) %>%
hc_xAxis(categories = df$Departamento,
tickLength = 0, lineWidth = 3, lineColor = "black",
labels = list(style = list(fontSize = "14px", fontWeight = "bold"))) %>%
hc_yAxis(title = list(text = "Porcentajes de postulantes"),
labels = list(format = "{value}%")) %>%
hc_tooltip(headerFormat = "<b> {point.key}</b><br>",
pointFormat = "Número de postulantes {series.name}: {point.y}<br> Número total: {point.total}<br>Porcentaje del total: {point.percentage:,.2f}%") %>%
hc_add_series(name=seg1_name, data = df$Masculino, color = color1) %>%
hc_add_series(name=seg2_name, data = df$Femenino, color = color2)Gráficos Combinados
Tip: Trabajar la variable FECHA, primero como as.yearmon(la cual proviene de la librería zoo), y después transformarla a character.
## Warning: package 'zoo' was built under R version 4.1.3
| Cuotas | Crecimiento | FECHA |
|---|---|---|
| 1914 | NA | ene 2022 |
| 1962 | -2.45 | feb 2022 |
| 1678 | 16.92 | mar 2022 |
| 2025 | -17.14 | abr 2022 |
| 1694 | 19.54 | may 2022 |
| 2437 | -30.49 | jun 2022 |
| 2317 | 5.18 | jul 2022 |
| 1617 | 43.29 | ago 2022 |
| 1798 | -10.07 | sep 2022 |
| 1728 | 4.05 | oct 2022 |
highchart()%>%
hc_yAxis_multiples(list(title=list(text= "Cuotas de Mercado",
style=list(fontWeight="bold", fontSize="auto")),
min=1500, max=2500,
labels=list(style=list(fontSize="auto", color="black")),
showFirstLabel=TRUE,showLastLabel=TRUE, opposite=FALSE),
list(title=list(text= "Tasa de Crecimiento (%)",
style=list(fontWeight="bold", fontSize="auto", color="#800000")),
min=-40, max=55,
labels=list(format="{value}%",style=list(fontSize="auto", color="black")),
showLastLabel=FALSE, opposite=TRUE)) %>%
hc_plotOptions(column=list(stacking="normal")) %>%
hc_add_series(AA,type = "column",name="Cuotas", hcaes(x=FECHA, y=Cuotas), yAxis=0,color="darkblue", dataLabeles=list(enable=TRUE, style=list(fontsize="auto"), color= "darkblue4"))%>%
hc_add_series(AA,type = "line",name="Tasa de var. mensual", hcaes(x=FECHA, y=Crecimiento), yAxis=1,color="#800000", dataLabeles=list(enable=TRUE, style=list(fontsize="auto"), color= "#800000")) %>%
hc_add_theme(hc_theme_bloom()) %>%hc_legend(enable=F)%>%
hc_xAxis(type="category",categories=AA$FECHA, labels = list(format = '{value:%B-%Y}'),
title = list(text = "Fecha", style = list(fontWeight = "bold", fontSize = "auto")))%>%
hc_exporting(enabled= TRUE)Gráficos de Dispersión
| Viaje | Tour | Pais |
|---|---|---|
| 25 | 1 | Perú |
| 47 | 3 | Perú |
| 13 | 1 | Perú |
| 60 | 3 | Perú |
| 64 | 4 | Colombia |
| 34 | 2 | Perú |
| 30 | 2 | Perú |
| 63 | 4 | Colombia |
| 100 | 5 | Colombia |
| 68 | 5 | Colombia |
Gráficos de Cajas y bigotes (box_plot)
| Viaje |
|---|
| 574 |
| 470 |
| 460 |
| 371 |
| 298 |
Box plot simple
box_stats <- boxplot.stats(ACP$Viaje)$stats
as <- highchart() %>%
hc_chart(type = "boxplot") %>%
hc_add_series(
name = "Mis Datos",
data = list(box_stats), # Wrap stats in list
color = "#0033CC"
) %>%
hc_title(text = "Boxplot simple") %>%
hc_yAxis(title = list(text = "Valores")) %>%
hc_xAxis(title = list(text = ""))
asBox plot personalizado
asl <- highchart() %>%
hc_chart(type = "boxplot") %>%
hc_add_series(
name = "Mis Datos",
data = list(box_stats), # Wrap stats in list
color = "blue", # Border color
fillColor = "lightblue", # Fill color inside the box
medianColor = "red" # Median line color
) %>%
hc_plotOptions(
boxplot = list(
fillColor = "lightblue", # Adds color inside the box
medianColor = "red", # Changes median line color
color = "blue" # Border color of the box
)
) %>%
hc_title(text = "Boxplot personalizado") %>%
hc_yAxis(title = list(text = "Valores")) %>%
hc_xAxis(title = list(text = ""))
asl