如何在ggplot中为指定坐标轴标签添加空白间隔?
解决方案
要在普通标签和加粗标签之间添加空白间隔,同时不修改原dataframe,可通过在x轴因子水平中插入一个无数据的空类别实现,具体修改如下:
修改后的完整代码
plot_data <- data.frame( Evaluation = rep(c("A", "B", "C"), each = 4), Mittari = rep(c("M1", "M2", "M3", "M4"), times = 3), value = runif(12), Kansallinen = runif(12) ) custom_labels <- c("\"Are you happy?\"", "\"Are you sad?\"", "\"Is the student happy?\"", "\"Is the student sad?\"") ss <- data.frame(Mittari = unique(plot_data$Mittari), custom_label = c("Yes", "Yes", "Agree", "Agree")) plot_data <- plot_data %>% left_join(ss, by = "Mittari") ggplot(plot_data, aes(x = factor(Mittari, levels = c("M1", "M2", "space", "M3", "M4")), y = value, fill = Evaluation)) + geom_bar(stat = "identity", position = position_dodge2(reverse = TRUE, width = 0.45)) + geom_vline(aes(xintercept = 0, color = 'National average')) + geom_errorbar(aes(ymin = Kansallinen, ymax = Kansallinen, group = Evaluation, width = 0.45), position = position_dodge2(reverse = TRUE)) + geom_text(aes(group = Mittari, y = 0.35, label = custom_label), size = 3.3, hjust = 0.5, vjust = -2.1, colour = "grey8") + scale_fill_manual(values = c("steelblue", "darkorange", "lightgreen")) + scale_color_manual(values = c("black", "steelblue", "darkorange")) + theme_minimal() + coord_flip() + scale_y_continuous(labels = scales::percent_format(scale = 100), breaks = seq(0, 1, by = 0.1), minor_breaks = NULL, limits = c(0, 1)) + scale_x_discrete(labels = c(custom_labels[1:2], "", custom_labels[3:4]), limits = c("M1", "M2", "space", "M3", "M4")) + labs(y = "", x = NULL, color = NULL) + guides(fill = guide_legend(order = 1), color = guide_legend(order = 2)) + theme(axis.text.y = element_text(face = c("plain", "plain", "plain", "bold", "bold"), color = "black"))
关键修改点
- 插入空类别:将x轴的
Mittari转换为包含空水平"space"的因子,在M2和M3之间生成无数据的位置,自然留出空白 - 设置空标签:在
scale_x_discrete中把空水平的标签设为空字符串,避免显示多余内容 - 调整字体样式:更新
axis.text.y的face参数,对应五个水平分别设置字体样式(前两个普通,中间空水平不影响,后两个加粗)
这种方法无需修改原dataframe结构,同时保证同类标签(M1-M2、M3-M4)之间的间距与原图表一致,仅在两类标签间增加空白。
内容的提问来源于stack exchange,提问作者Billyboy
相关产品推荐
相关产品推荐

