如何在ggplot2中在没有数据的情况下在y轴上添加额外标签

时间:2018-10-11 23:07:22

标签: r ggplot2

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

Coef Plot

我要进一步做的是添加额外的变量,而y轴上没有任何数据。例如,在标签FeatGender的顶部放置标签FeatGenderMale,或者在另一个示例中,在标签FeatEU和{的标签之间放置标签FeatPartyIDLiberal Democrats。 {1}}。以下是数据的简化版本:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这是一种先将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")

enter image description here