R ggplot2:使用expand_limits(x=0)后如何仅移除零刻度标签?
解决ggplot中移除x轴零刻度标签并保留左侧间距的问题
方法1:保留零刻度线但隐藏标签
通过scale_x_continuous的labels参数,将0对应的标签替换为空字符串,既保留expand_limits(x=0)带来的左侧间距,又不显示零标签:
library(ggplot2) # 定义自适应整数刻度的函数 integer_breaks <- function(n = 5, ...) { function(x) { pretty(x, n, ...) %>% unique() %>% round() } } # 示例数据 xxx <- c(1, 2, 4, 1, 1, 4, 2, 4, 1, 1, 3, 3, 4 ) yyy <- c(11, 22, 64, 45, 76, 47, 23, 44, 65, 86, 87, 83, 56 ) data <- data.frame(xxx, yyy) # 绘制图表 p <- ggplot(data, aes(x = xxx, y = yyy)) + geom_count(color = "blue") + expand_limits(x = 0) + scale_x_continuous( breaks = integer_breaks(), labels = function(breaks) ifelse(breaks == 0, "", breaks) ) p
方法2:直接移除零刻度(含刻度线和标签)
修改整数刻度函数,过滤掉0这个刻度值,同时保留expand_limits(x=0)的左侧间距:
library(ggplot2) # 定义过滤掉零的整数刻度函数(base R写法,无需额外包) integer_breaks_no_zero <- function(n = 5, ...) { function(x) { pretty(x, n, ...) %>% unique() %>% round() %>% .[. != 0] } } # 示例数据 xxx <- c(1, 2, 4, 1, 1, 4, 2, 4, 1, 1, 3, 3, 4 ) yyy <- c(11, 22, 64, 45, 76, 47, 23, 44, 65, 86, 87, 83, 56 ) data <- data.frame(xxx, yyy) # 绘制图表 p <- ggplot(data, aes(x = xxx, y = yyy)) + geom_count(color = "blue") + expand_limits(x = 0) + scale_x_continuous(breaks = integer_breaks_no_zero()) p
方法3:不用expand_limits,通过扩展参数实现左侧间距
如果不想依赖expand_limits,可以用scale_x_continuous的expand参数直接设置左侧扩展到0的位置,同时配合过滤零的刻度函数:
library(ggplot2) integer_breaks_no_zero <- function(n = 5, ...) { function(x) { pretty(x, n, ...) %>% unique() %>% round() %>% .[. != 0] } } # 示例数据 xxx <- c(1, 2, 4, 1, 1, 4, 2, 4, 1, 1, 3, 3, 4 ) yyy <- c(11, 22, 64, 45, 76, 47, 23, 44, 65, 86, 87, 83, 56 ) data <- data.frame(xxx, yyy) # 计算左侧需要扩展的长度:从数据最小x值到0的距离 left_expand <- min(data$xxx) p <- ggplot(data, aes(x = xxx, y = yyy)) + geom_count(color = "blue") + scale_x_continuous( breaks = integer_breaks_no_zero(), expand = expansion(add = c(left_expand, 0)) # 左侧扩展到0,右侧不扩展 ) p
内容的提问来源于stack exchange,提问作者Abiologist
相关产品推荐
相关产品推荐

