2

在下面的图中,我想避开彩色形状,但不是为了1让虚线与1. 需要避开彩色形状,以免它们在同一时间点相互重叠。这是生成虚拟数据和绘图的代码。有没有办法选择性地躲避相同的点geom_point

df <- data.frame(id = factor(sort(rep(seq(1,5),2))),
                 time = rep(c(3,6), 5),
                 cat1 = c(sample(c('good', 'ok', 'bad'), 2),
                          sample(c('good', 'ok', 'bad'), 2),
                          sample(c('good', 'ok', 'bad'), 2),
                          sample(c('good', 'ok', 'bad'), 2),
                          sample(c('good', 'ok', 'bad'), 2)),
                 cat2 = c(sample(c('a', 'b', 'c', 'd'), 2), 
                          sample(c('a', 'b', 'c', 'd'), 2),
                          sample(c('a', 'b', 'c', 'd'), 2),
                          sample(c('a', 'b', 'c', 'd'), 2),
                          sample(c('a', 'b', 'c', 'd'), 2))) %>%
  pivot_longer(cols = c('cat1', 'cat2'), names_to='type', names_prefix = 'value', values_to = 'value') %>%
  plyr::rbind.fill(data.frame(id = factor(seq(1,5)), 
        time = 9,
        time2 = 9,
        type = 'off',
        value = c(1, NA, NA, 1, 1))) %>%
  dplyr::arrange(id, time)

ggplot(df, aes(x = id, y = time)) +
  geom_point(aes(id, time, colour = value, shape = value), size = 2, position = position_dodge(width = 0.7)) +
  geom_segment(data = df[df$type == 'off',], aes(x = id, xend = id, y = 6,
                                          yend = time2), colour = 'black', linetype = 'dotted') +
  coord_flip() +
  scale_shape_manual(values = c(13, 17, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15)) +
  scale_colour_manual(values = c('black', 'purple', 'green', '#ffff66', 'red',
                                 'green', '#ffff66', 'red', 
                                 'green', '#ffff66', 'pink')) +
  guides(fill = guide_legend(order = 2), shape = guide_legend(override.aes = list(size = 3)))

在此处输入图像描述

4

1 回答 1

0

防止一个(或多个)点躲避的一种方法是进行两次geom_point()呼叫:一个被躲避(并且不包括所讨论的点,另一个没有被躲避并且包括该点

ggplot(df, aes(x = id, y = time)) +
  geom_point(
    data = subset(df, value=="1"),
    aes(colour = value, shape = value), size = 2) +
  geom_point(
    data = subset(df, value!="1"),
    aes(colour = value, shape = value),
    size = 2, position = position_dodge(width = 0.7)) +
  
  geom_segment(data = df[df$type == 'off',], aes(x = id, xend = id, y = 6,
                                                 yend = time2), colour = 'black', linetype = 'dotted') +
  coord_flip() +
  scale_shape_manual(values = c(13, 17, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15)) +
  scale_colour_manual(values = c('black', 'purple', 'green', '#ffff66', 'red',
                                 'green', '#ffff66', 'red', 
                                 'green', '#ffff66', 'pink')) +
  guides(fill = guide_legend(order = 2), shape = guide_legend(override.aes = list(size = 3)))

在此处输入图像描述

只要数据的映射方式相同,它们在图例中的显示方式就会与您最初的方式相同。另请注意,无需在aes()for中再次包含 x 和 y geom_point()。您可以在此处指定,但如果您不这样做,该函数将查找全局定义的映射(即,在ggplot(aes(...))其中进行分配的映射。

于 2022-02-18T03:04:09.563 回答