I'm trying to create a scatter plot with ggplot, and I would like the y axis to cross the x axis at x = 0, instead of being at the left of the plot.
Here's an example of what I'm trying to achieve :
Here's a reproducible example
library(ggplot2)
library(ggrepel)
set.seed(123)
data_filtered <- mtcars
data_filtered$evolution <- data_filtered$mpg - mean(data_filtered$mpg)
data_filtered$tauxpourmille <- data_filtered$hp / 100
data_filtered$facts <- data_filtered$wt * 1000
data_filtered$Code.region <- sample(1:3, nrow(data_filtered), replace = TRUE)
data_filtered$Code.departement <- rownames(mtcars)
data_filtered <- data_filtered %>%
group_by(Code.region) %>%
slice_head(n = 2) %>%
ungroup()
region_colors <- c("1" = "red3", "2" = "blue4", "3" = "green3")
ggplot(data_filtered, aes(x = evolution, y = tauxpourmille, size = facts, color = factor(Code.region))) +
geom_point(shape = 1, stroke = 1.3, alpha = 0.6) +
geom_text_repel(aes(label = Code.departement),
box.padding = 3,
size = 5,
min.segment.length = 0,
force = 20,
segment.size = 0.5) +
labs(x = "Evolution",
y = "Horsepower/100") +
theme_minimal() +
scale_color_manual(values = region_colors) +
scale_size_area(max_size = 10) +
guides(size = "none") +
theme(axis.title.x = element_text(),
axis.title.y = element_text(),
legend.position = "none") +
expand_limits(x = range(data_filtered$evolution) + c(-0.3, 0.3) * diff(range(data_filtered$evolution)),
y = range(data_filtered$tauxpourmille) + c(-0.3, 0.3) * diff(range(data_filtered$tauxpourmille)))
Thank you.
You could use the coord_axes_inside
function from the ggh4x
package to place the y axis at 0 like this:
library(ggplot2)
library(ggrepel)
library(ggh4x)
ggplot(data_filtered, aes(x = evolution, y = tauxpourmille, size = facts, color = factor(Code.region))) +
geom_point(shape = 1, stroke = 1.3, alpha = 0.6) +
geom_text_repel(aes(label = Code.departement),
box.padding = 3,
size = 5,
min.segment.length = 0,
force = 20,
segment.size = 0.5) +
labs(x = "Evolution",
y = "Horsepower/100") +
theme_minimal() +
scale_color_manual(values = region_colors) +
scale_size_area(max_size = 10) +
guides(size = "none") +
theme(axis.title.x = element_text(),
axis.title.y = element_text(),
legend.position = "none") +
expand_limits(x = range(data_filtered$evolution) + c(-0.3, 0.3) * diff(range(data_filtered$evolution)),
y = range(data_filtered$tauxpourmille) + c(-0.3, 0.3) * diff(range(data_filtered$tauxpourmille))) +
coord_axes_inside(labels_inside = TRUE)
Created on 2024-05-16 with reprex v2.1.0