在下面的圖中,我想避開彩色形狀,但不是為了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)))

uj5u.com熱心網友回復:
防止一個(或多個)點躲避的一種方法是進行兩次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(...))其中進行分配的映射。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427627.html
