r - Place text next to dodged points
问题描述
I try to plot the estimates of a regression model using ggplot2.
I was able to plot the estimates and the confidence interval of the categories of two variables but I was not able to put text next to the points.
Here is my data:
structure(list(variable = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L), .Label = c("age_cat", "sex"), class = "factor"), category = c("16-30",
"31-45", "46-60", "61-75", "75+", "male", "female"), prob = c(49.1490864780164,
45.0134864230846, 41.3423868452015, 43.9898075415967, 30.4938196116868,
44.2540954584486, 37.1385779594009), lower = c(36.7707494786309,
39.1561531165008, 36.9823398823282, 39.452968108129, 23.006030817612,
41.140305397387, 32.4225011064077), upper = c(61.6326443483847,
51.0123993228346, 45.8425298018043, 48.6293365972465, 39.1785626239475,
47.4137151233817, 42.1131460129666)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -7L))
# A tibble: 7 x 5
variable category prob lower upper
<fct> <chr> <dbl> <dbl> <dbl>
1 age_cat 16-30 49.1 36.8 61.6
2 age_cat 31-45 45.0 39.2 51.0
3 age_cat 46-60 41.3 37.0 45.8
4 age_cat 61-75 44.0 39.5 48.6
5 age_cat 75+ 30.5 23.0 39.2
6 sex male 44.3 41.1 47.4
7 sex female 37.1 32.4 42.1
This is what I tried:
library(ggplot2)
ggplot(data = my_data, aes(x = variable, y = prob)) +
geom_pointrange(aes(ymin = lower, ymax = upper, group = category),
position = position_dodge(width = 0.4)) +
geom_text(aes(y = 10, label = category)) +
ylim(0, NA) +
coord_flip()
I would like to have the factor levels on the same level as the points. I tried , position = position_dodge(width = 0.4)
within geom_text
or position = identity
but I did not manage to get the names of the categories where I want them to be.
解决方案
确保还包括group
在您的aes
:
library(ggplot2)
ggplot(data = my_data, aes(x = variable, y = prob)) +
geom_pointrange(aes(ymin = lower, ymax = upper, group = category),
position = position_dodge(width = .4)) +
geom_text(aes(y = 10, group = category, label = category), position = position_dodge(width=.4)) +
ylim(0, NA) +
coord_flip()
推荐阅读
- python - 在本地化页面中删除缓存的问题
- android - android.widget.SelectionActionModeHelper$TextClassificationHelper.init (SelectionActionModeHelper.java:974)
- python - 任何人都知道使用python获取instagram帖子网址的方法(不是图片或视频的网址,而是整个帖子)
- python - 删除了 python 并尝试使用 WSL 重新安装它但无法
- mongodb - 如何从 mongo 集合中的数组属性中删除元素
- flutter - 如何将 Flutter speech_to_text 依赖项用于英语以外的语言。例如:阿姆哈拉语(埃塞俄比亚当地语言)
- python - Pip 包(钟摆 2.1)安装失败并出现 FileNotFoundError
- php - Woocommerce 订阅:更改付款方式应该有 0 订阅费
- regex - 字符串的正则表达式,并且不能在某个位置包含数字
- python-3.x - 当我尝试在 Pygame 中使用鼠标事件和按键事件时,它不起作用