如何去除ggplot中facet_wrap标签间的水平线?
去除ggplot分面标签中州名与城市名间的水平线
使用ggplot绘制三面板图形时,通过facet_wrap(~state+city)按州和城市分组,分面标签里州名和城市名之间会自动出现一条水平线,以下是解决方法:
示例代码与问题图
library(tidyverse) set.seed(333) # 示例数据集 df <- data.frame( state = c("North Carolina","North Carolina","North Carolina", "North Carolina","North Carolina","North Carolina", "Virginia","Virginia","Virginia"), city = c("Boone","Boone","Boone", "Elizabeth City","Elizabeth City","Elizabeth City", "Norfolk","Norfolk","Norfolk"), year = rep(seq(2000,2004,2),3), value = round(rnorm(9,100,50)) ) # 存在问题的绘图代码(州名与城市名间有水平线) df %>% ggplot(aes(x = year, y = value)) + geom_point() + theme_bw() + facet_wrap(~state+city)

创建于2024年4月19日,使用reprex v2.1.0
解决方案
方法1:提前合并州名与城市名为单个字段
state+city会被ggplot识别为两个独立变量,因此自动添加分隔线。提前将两者合并为一个新字段,再用于分面即可消除分隔线:
# 新增合并后的分面标签字段 df <- df %>% mutate(facet_label = paste(state, city, sep = " ")) # 使用新字段分面 df %>% ggplot(aes(x = year, y = value)) + geom_point() + theme_bw() + facet_wrap(~facet_label)
方法2:自定义分面标签生成函数
无需修改数据集,通过labeller参数自定义标签逻辑,直接合并两个变量的文本:
df %>% ggplot(aes(x = year, y = value)) + geom_point() + theme_bw() + facet_wrap(~state+city, labeller = labeller(.default = function(x) gsub("\\.", " ", x)))
内容的提问来源于stack exchange,提问作者tassones
相关产品推荐
相关产品推荐

