如何在ggplot2中设置y轴与x轴在x=0处交叉?

问题描述 投票:0回答:1

我正在尝试使用 ggplot 创建散点图,我希望 y 轴在 x = 0 处与 x 轴交叉,而不是位于图的左侧。

这是我想要实现的目标的示例:

图表取自INSEE

这是一个可重现的示例

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)))

谢谢你。

r ggplot2 graphics axis
1个回答
0
投票

您可以使用

[coord_axes_inside](https://teunbrand.github.io/ggh4x/articles/Miscellaneous.html)
包中的
ggh4x
函数将 y 轴放置在 0 处,如下所示:

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)

创建于 2024-05-16,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.