library(tidyverse)Tidyverse - Graph
Load the library
Plotting two columns in a bar graph
# Plot a bar chart with two diffeent colomn ------------------------
# Your tibble
my_tibble <- tibble(milieu_naturel = 20.82, Milieu_bati = 5.97)
# Convert the tibble to long format for plotting
my_tibble_long <- pivot_longer(my_tibble, cols = everything(), names_to = "category", values_to = "value")
# Rename the factor levels for the category
my_tibble_long$category <- factor(my_tibble_long$category,
levels = c("milieu_naturel", "Milieu_bati"),
labels = c("Milieu naturel", "Milieu bâti"))
# Define custom colors
custom_colors <- c("Milieu naturel" = "#1b9e77", "Milieu bâti" = "#d95f02")
# Create the bar plot with labels on the bars in black color
ggplot(my_tibble_long, aes(x = category, y = value, fill = category)) +
geom_bar(stat = "identity") +
geom_text(aes(label = value), vjust = 2, color = "black", size =5) + # Black labels
scale_fill_manual(values = custom_colors) +
labs(title = "Comparaison entre Milieu naturel et Milieu bâti",
x = "Occupation",
y = "Hectare",
fill = "Occupation / ha") + # Rename the legend title
theme_minimal() +
theme(text = element_text(size = 14),
axis.title = element_text(size = 12),
axis.text = element_text(size = 12),
plot.title = element_text(size = 12))How to plot a Pie chart
#| warning: false
# Plot a Pie chart -----------------------------------------
# Load the tidyverse package
library(tidyverse)
# Your tibble
my_tibble <- tibble(milieu_naturel = 20.82, Milieu_bati = 5.97)
# Convert the tibble to long format for plotting
my_tibble_long <- pivot_longer(my_tibble, cols = everything(), names_to = "category", values_to = "value")
# Rename the factor levels for the category
my_tibble_long$category <- factor(my_tibble_long$category,
levels = c("milieu_naturel", "Milieu_bati"),
labels = c("Milieu naturel", "Milieu bâti"))
# Calculate the sum of all values
total_sum <- sum(my_tibble_long$value)
# Define a common font size
common_font_size <- 14
legend_font_size <- 14 # Font size for legend labels
# Create the pie chart with a renamed legend title and adjusted legend label sizes
ggplot(my_tibble_long, aes(x = "", y = value, fill = category)) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
geom_text(aes(label = paste0(round(value / total_sum * 100, 1), "%")),
position = position_stack(vjust = 0.5),
size = common_font_size * 0.5) +
labs(title = "Distrubution entre milieu bâti et milieu naturel",
x = "",
y = "",
fill = "Distribution en %") + # Rename the legend title
theme_void() +
theme(text = element_text(size = common_font_size),
plot.title = element_text(size = common_font_size * 1),
legend.text = element_text(size = legend_font_size)) + # Adjust legend label size
scale_fill_manual(values = c("Milieu naturel" = "#1b9e77", "Milieu bâti" = "#d95f02")) # Custom colors