You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中设置Y轴于x=0处与X轴相交?

调整ggplot散点图Y轴至x=0处的实现方案

要让Y轴在x=0位置与X轴相交(而非默认的绘图区域左侧),可以通过以下修改实现:

核心修改点

  1. 定位Y轴线条到x=0位置
  2. 调整Y轴刻度与标签的显示位置,避免重叠
  3. 关闭绘图区域裁剪,防止元素被截断
  4. 按需补充坐标轴线条(因theme_minimal默认无坐标轴)

修改后的完整代码

library(ggplot2)
library(ggrepel)
library(dplyr)

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_classic减少坐标轴自定义工作量,默认包含坐标轴线条
    theme_classic() +
    scale_color_manual(values = region_colors) +
    scale_size_area(max_size = 10) +
    guides(size = "none") +
    theme(
        axis.title.x = element_text(),
        # 调整Y轴标题边距,避免与刻度重叠
        axis.title.y = element_text(margin = margin(r = 10)),
        legend.position = "none",
        # 关键:将Y轴线条定位在x=0处
        axis.line.y = element_line(xintercept = 0),
        # 让Y轴刻度标签显示在新Y轴右侧
        axis.text.y = element_text(margin = margin(r = 5)),
        # 预留足够边距,防止元素被截断
        plot.margin = margin(10, 10, 10, 10)
    ) +
    # 关闭裁剪,确保所有元素正常显示
    coord_cartesian(clip = "off") +
    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)))

若坚持使用theme_minimal的适配代码

如果需要保留theme_minimal的风格,需手动添加X轴线条,修改部分如下:

# 替换原theme_classic()为以下内容
theme_minimal() +
theme(
    axis.line.x = element_line(), # 手动添加X轴线条
    axis.line.y = element_line(xintercept = 0),
    axis.text.y = element_text(margin = margin(r = 5)),
    axis.title.y = element_text(margin = margin(r = 10)),
    legend.position = "none",
    plot.margin = margin(10, 10, 10, 10)
)

内容的提问来源于stack exchange,提问作者NoNameBoyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 01:19:51