Autor: Álvaro Alonso Fernández
Departamento de Ciencias de la Vida
Universidad de Alcalá (España)
Queremos realizar un gráfico de sectores o de quesitos. Es un gráfico adecuado para mostrar porcentajes. No suele ser muy empleado en ciencia, ya que no se puede mostrar medidas de desviación. Pero si tenemos que mostrar un porcentraje (sobre 100) es muy adecuado.
Creamos nuestro datframe con los siguientes datos:
mi_datos <- data.frame(
"Valores" = 1:4,
"Ciudad" = c("Alicante", "Valencia", "Madrid", "Barcelona"),
"Numeros" = c(10, 35, 40, 15),
"Posiciones" = as.character(c("4", "2", "1", "3"))
)
mi_datos
## Valores Ciudad Numeros Posiciones
## 1 1 Alicante 10 4
## 2 2 Valencia 35 2
## 3 3 Madrid 40 1
## 4 4 Barcelona 15 3
Vamos a utilizar la variable Numeros
que es la que tienen los porcentajes que nos interesa representar. Ahora cargamos las librerias necesarias:
library(ggplot2)
## Warning: replacing previous import 'lifecycle::last_warnings' by
## 'rlang::last_warnings' when loading 'tibble'
## Warning: replacing previous import 'lifecycle::last_warnings' by
## 'rlang::last_warnings' when loading 'pillar'
library(tidyverse)
## Warning: replacing previous import 'lifecycle::last_warnings' by
## 'rlang::last_warnings' when loading 'hms'
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v tibble 3.1.1 v dplyr 1.0.6
## v tidyr 1.2.0 v stringr 1.4.0
## v readr 1.4.0 v forcats 0.5.1
## v purrr 0.3.4
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
Vamos a hacer el histograma más sencillo posible, en este caso solamente vamos a representar los valores que toma la Var1
. Veamos que aspecto toma nuestro gráfico:
ggplot(mi_datos,aes(x="",y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",color="white")+
coord_polar(theta="y")
Para ello utilizamos geom_text
:
ggplot(mi_datos,aes(x="",y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",color="white")+
coord_polar(theta="y")+
geom_text(aes(label=Numeros),
position=position_stack(vjust=0.5),color="black",size=6)+
coord_polar(theta = "y")
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.
Mejoramos la apariencia general de la figura. Podemos personalizar los colores con scale_Fill_manual
y añadir un título a la figura por medio de labs
y title
. Para ello:
library (scales)
##
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
##
## discard
## The following object is masked from 'package:readr':
##
## col_factor
ggplot(mi_datos,aes(x="",y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",
color="white")+
geom_text(aes(label=percent(Numeros/100)),
position=position_stack(vjust=0.5),color="white",size=5)+
coord_polar(theta = "y")+
scale_fill_manual(values=c("blue","red","darkgreen","black"))+
theme_void()+
labs(title="Gráfico de Quesitos")
De forma muy sencilla quitando coord_polar(theta = "y")+
:
ggplot(mi_datos,aes(x="",y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",
color="white")+
geom_text(aes(label=percent(Numeros/100)),
position=position_stack(vjust=0.5),color="white",size=5)+
scale_fill_manual(values=c("blue","red","darkgreen","black"))+
theme_void()+
labs(title="Gráfico de Barra")
Para ello añadimos de nuevo el coord_polar(theta = "y")
y ponemos un xlim
con 0.5 y 3.5:
ggplot(mi_datos,aes(x=2,y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",
color="white")+
geom_text(aes(label=percent(Numeros/100)),
position=position_stack(vjust=0.5),color="white",size=5)+
coord_polar(theta = "y")+
scale_fill_manual(values=c("blue","red","darkgreen","black"))+
theme_void()+
labs(title="Gráfico de Quesitos")+
xlim(0.5,3.5)
Podemos ir mejorando la leyenda, personalizar los nombres de la leyenda scale_fill_discrete(labels = c("MADRID", "VITIGUDINO", "TERUEL", "SORIA"))
y cambiar la posición de la leyenda theme(legend.position = "bottom")
:
ggplot(mi_datos,aes(x=2,y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",
color="white")+
geom_text(aes(label=percent(Numeros/100)),
position=position_stack(vjust=0.5),color="white",size=5)+
coord_polar(theta = "y")+
scale_fill_manual(values=c("blue","red","darkgreen","black"))+
theme_void()+
labs(title="Gráfico de Quesitos")+
xlim(0.5,3.5)+
scale_fill_discrete(labels = c("MADRID", "VITIGUDINO", "TERUEL", "SORIA"))+
theme(legend.position = "bottom")
## Scale for 'fill' is already present. Adding another scale for 'fill', which
## will replace the existing scale.
ggplot(mi_datos,aes(x="",y=Numeros, fill=Ciudad))+
geom_bar(stat = "identity",
color="white")+
geom_text(aes(label=percent(Numeros/100)),
position=position_stack(vjust=0.5),color="white",size=5)+
scale_fill_manual(values=c("blue","red","darkgreen","black"))+
theme_void()+
labs(title="Gráfico de Barra") +
theme(legend.position = "bottom")
Utilizamos lessR
para dibujar nuestro histograma. Cargamos la libreria por medio de library(lessR)
. La forma más sencilla de hacerlo sería utilizando la orden pie
:
library(lessR)
##
## lessR 4.2.0 feedback: gerbing@pdx.edu
## --------------------------------------------------------------
## > d <- Read("") Read text, Excel, SPSS, SAS, or R data file
## d is default data frame, data= in analysis routines optional
##
## Learn about reading, writing, and manipulating data, graphics,
## testing means and proportions, regression, factor analysis,
## customization, and descriptive statistics from pivot tables.
## Enter: browseVignettes("lessR")
##
## View changes in this or recent versions of lessR.
## Enter: help(package=lessR) Click: Package NEWS
## Enter: interact() for access to interactive graphics
## New function: reshape_long() to move data from wide to long
##
## Attaching package: 'lessR'
## The following object is masked from 'package:scales':
##
## rescale
## The following objects are masked from 'package:dplyr':
##
## recode, rename
pie(mi_datos$Numeros)
pie(mi_datos$Numeros, labels = mi_datos$Numeros)
En este caso elegimos los coloresz del 1 al 4 con col
y el tamaño de los números por medio de cex
:
pie(mi_datos$Numeros, labels = mi_datos$Numeros, col = 1:4, cex = 3)
El borde de los quesitos en el mismo color que el quesito por medio de border = 1:4
:
pie(mi_datos$Numeros, labels = mi_datos$Numeros, col = 1:4, cex = 3, border = 1:4)
Cambiamos la densidad de los quesitos por medio de density = 175
:
pie(mi_datos$Numeros, labels = mi_datos$Numeros, col = 1:4, cex = 3, border = 1:4, density = 175)
Para ello calculamos primero el porcentaje (en este caso es fácil pero lo dejo por si el conjunto de vuestros datos no suma 100%). Una vez calculados y guardados en porcentajes
los incluimos en la figura por medio de labels = porcentajes
:
porcentajes <- paste0(round(100 * mi_datos$Numeros/sum( mi_datos$Numeros), 2), "%")
porcentajes
## [1] "10%" "35%" "40%" "15%"
pie(mi_datos$Numeros, labels = porcentajes, col = 1:4, cex = 3, border = 1:4, density = 175)
Departamento de Ciencias de la Vida
Universidad de Alcalá (España)