首页 > 解决方案 > 如何在 ggplot2 中没有数据的 y 轴上添加额外标签

问题描述

我正在制作一个显示两组回归系数和标准误差的图,图表如下:

系数图

我想要进一步做的是在 y 轴上添加没有任何数据的额外变量。例如,在 labelFeatGender的顶部放置一个标签FeatGenderMale,或者在另一个示例中,FeatEU在 label ofFeatPartyIDLiberal Democrats和 of 的标签之间放置一个标签FeatEUIntegrationSupportEUIntegration。以下是精简版数据:

          coef         se          low         high    sex
1  -0.038848364 0.02104994 -0.080106243  0.002409514 Female
2   0.095831201 0.02793333  0.041081877  0.150580526 Female
3   0.050972670 0.02828353 -0.004463052  0.106408391 Female
4  -0.183558492 0.02454943 -0.231675377 -0.135441606 Female
5   0.044879447 0.02712518 -0.008285914  0.098044808 Female
6 -0.003858672 0.03005477 -0.062766024  0.055048681   Male
7  0.003048763 0.04687573 -0.088827676  0.094925203   Male
8  0.015343897 0.03948959 -0.062055700  0.092743494   Male
9 -0.132600259 0.04146323 -0.213868197 -0.051332322   Male
10 -0.029764559 0.04600719 -0.119938650  0.060409533   Male

这是我的代码:

v_name <- c("FeatGenderMale", "FeatPartyIDLabourParty", "FeatPartyIDLiberalDemocrats", 
            "FeatEUIntegrationOpposeEUIntegration", "FeatEUIntegrationSupportEUIntegration")

t <- ggplot(temp, aes(x=c(v_name,v_name), y=coef, group=sex, colour=sex))

t + 
  geom_point(position = position_dodge(width = 0.3)) + 
  geom_errorbar(aes(ymin = low, ymax = high, width = 0), position = position_dodge(0.3)) + 
  coord_flip() + 
  scale_x_discrete(limits = rev(v_name)) + 
  geom_hline(yintercept = 0.0, linetype = "dotted") + 
  theme(legend.position = "bottom")

谢谢您的帮助!

标签: rggplot2

解决方案


这是一种方法,首先将 应用v_name到源数据框中,然后使用更长的附加版本的v_name向量作为轴。

library(ggplot2); library(dplyr)
# Add the v_name into the table
temp2 <- temp %>% group_by(sex) %>% mutate(v_name = v_name) %>% ungroup() 

# Make the dummy label for axis with add'l entries
v_name2 <- append(v_name, "FeatGender", after = 0)
v_name2 <- append(v_name2, "FeatEU", after = 4)

# Plot using the new table
t <- ggplot(temp2, aes(x=v_name, y=coef, group=sex, colour=sex))
t + 
  geom_point(position = position_dodge(width = 0.3)) + 
  geom_errorbar(aes(ymin = low, ymax = high, width = 0), position = position_dodge(0.3)) + 
  coord_flip() + 
  # ... but use the larger list of axis names
  scale_x_discrete(limits = rev(v_name2)) + 
  geom_hline(yintercept = 0.0, linetype = "dotted") + 
  theme(legend.position = "bottom")

在此处输入图像描述


推荐阅读