R语言 我可以绘制两个geom_segments,按组彼此移位吗?

pokxtpni  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(79)

我希望产生一个图与箭头描绘的大小之间的两个值的性别。我自然希望这两支箭相互错位。

data <- data.frame(sex  = c('Men', 'Men', 'Men', 'Men', 'Men', 'Women','Women','Women','Women','Women'),
                    age = c('00-49', '50-59', '60-69', '70-79', '80-89', '00-49', '50-59', '60-69', '70-79', '80-89'),
                    obs_1 = c(42.73, 12.97, 11.87, 10.34, 5.39, 49.29 , 17.69, 14.41, 10.80, 6.49),
                    obs_2 = c(15.88, 28.16, 25.98, 25.55, 18.91,21.57, 38.28, 35.28, 30.10, 23.09)
                  )

使用geom_segment我得到了我想要的箭头,但是它们会彼此重叠

data %>% 
  ggplot(aes(color = sex)) +
  geom_segment(aes(x = obs_1, xend = obs_2,
                   y = age, yend = age), linewidth = 1.2, 
               arrow = arrow(type = 'closed', length = unit(3.5, 'mm')) 
  )

我知道类似的问题已经在这里得到了解决,一个解决方案是使用geom_linerange和position_dodge2,但是这样我就不能得到我想要的箭头了。

data %>%
  ggplot(aes(x = age, color = sex,
                 ymin = obs_1,
                 ymax = obs_2)) +
  geom_linerange(linewidth = 1, position = position_dodge2(width = 0.5)) +
  coord_flip()
brccelvz

brccelvz1#

geom_segment通常与连续刻度一起使用,因此您可以将年龄作为连续变量,并根据性别手动添加一点空间。

library(tidyverse)

data <- data.frame(sex  = c('Men', 'Men', 'Men', 'Men', 'Men', 'Women','Women','Women','Women','Women'),
                   age = c('00-49', '50-59', '60-69', '70-79', '80-89', '00-49', '50-59', '60-69', '70-79', '80-89'),
                   obs_1 = c(42.73, 12.97, 11.87, 10.34, 5.39, 49.29 , 17.69, 14.41, 10.80, 6.49),
                   obs_2 = c(15.88, 28.16, 25.98, 25.55, 18.91,21.57, 38.28, 35.28, 30.10, 23.09)) %>%
  mutate(age=factor(age),
         age2=as.numeric(age)+c(Men=.1, Women=-0.1)[sex])

data %>%
  ggplot(aes(color = sex)) +
  geom_segment(aes(x = obs_1, xend = obs_2, y = age2, yend = age2),
               linewidth = 1.2,
               arrow = arrow(type = 'closed', length = unit(3.5, 'mm'))) +
  scale_y_continuous(breaks=seq_len(nlevels(data$age)), labels=levels(data$age))

相关问题