首页 > 解决方案 > 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()

enter image description here

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.

标签: rggplot2

解决方案


确保还包括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()

带有文本标签的绘图


推荐阅读