Pie charts, also known as circle charts, are a commonly used tool in data analysis to show the distribution of different variables in a data set. RStudio is a popular software for data visualization and offers several tools to easily create pie charts.
The following are the steps to create a pie chart in R:
- Installation and loading of the ggplot2 package.
install.packages("ggplot2")
2. library(ggplot2)
loads the ggplot2 package into the current R workspace.
library(ggplot2)
3. datos <- data.frame(Sector = c(...), Porcentaje = c(...))
creates a data frame called datos
with two columns: Sector
and Porcentaje
.
datos <- data.frame(Sector = c("Suministro de electricidad y agua", "Acuicultura y pesca de camarón", "Alojamiento y servicios de comida", "Pesca", "Transporte", "Comercio"),
Porcentaje = c(0.269, 0.222, 0.194, 0.118, 0.108, 0.102))
4. Creating the pie or circular chart:
- data <- data.frame(Sector = c(…), Porcentaje = c(…)): creates a data frame called “data” with two columns: Sector and Porcentaje.
- p <- ggplot(data, aes(x=””, y=Porcentaje, fill=Sector)) + …: creates a graph object called “p” using ggplot2. The graph is based on the data frame “data” and aesthetic mappings (aes) are set for x, y, and fill.
- geom_bar(width = 1, stat = “identity”): adds a layer of bars to the graph with a width of 1 and an “identity” state.
- coord_polar(“y”, start=0): sets the polar coordinates for the y-axis with a starting point at 0.
- scale_fill_brewer(palette = “Paired”): sets the fill scale to use the Paired palette from RColorBrewer.
- ggtitle(“Distribución del PIB por sector”), xlab(“”) and ylab(“Porcentaje”): set the title, x-axis label, and y-axis label for the graph, respectively.
- theme_void(): sets an empty theme for the graph.
- geom_text(aes(label=paste(round(100 * Porcentaje, 2), “%”)), position = position_stack(vjust = 0.5)): adds a layer of text to the graph with the corresponding percentages for each section of the pie chart, with a vertical justification of 0.5.
- theme(plot.title = element_text(hjust = 0.5, face = “bold”, family = “Times New Roman”)): sets the title property of the graph with a horizontal alignment of 0.5, bold font, and “Times New Roman” font family.
p <- ggplot(datos, aes(x="", y=Porcentaje, fill=Sector)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0) +
scale_fill_brewer(palette = "Paired") +
ggtitle("Distribución del PIB por sector") +
xlab("") +
ylab("Porcentaje") +
theme_void() +
geom_text(aes(label=paste(round(100 * Porcentaje, 2), "%")), position = position_stack (vjust = 0.5)) +
theme(plot.title = element_text(hjust = 0.5, face = "bold", family = "Times New Roman"))
5. Finally, use the ggsave
function to save the graph.
ggsave("grafico_torta.png", plot = p, width = 6, height = 4)
Made with ChatGPT