r - 如何在 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")
谢谢您的帮助!
解决方案
这是一种方法,首先将 应用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")
推荐阅读
- laravel - 尝试连接到生产 Pgsql 数据库但连接超时 (0x0000274C/10060)
- angular - @angular-devkit/build-angular 未找到
- python - Lower Objective leads to better solution MILP
- apache-kafka - Node-Red 中的“KafkaJSProtocolError:组成员支持的协议与现有成员的协议不兼容”错误
- php - Symfony Secrets 正在减慢每个页面的加载速度
- flutter - 在 initState 中同时调用两个事件
- java - Maven 测试命令发现的测试比测试文件夹包含的更多
- outlook - 使用 office.js 在邮件项目上设置自定义图标
- sql - 在 Moodle 中连接到数据库失败
- flutter - Inkwell onTap 在 ListView.builder 中不起作用