使用标签作为点标记,而不是使用单独的标签呢?这是一个使用ggplot2
而不是基本图形的示例。
为了避免重叠,我们直接设置重复值的垂直偏移量,而不是让它随机抖动。为此,我们需要分配数字 y 值(以便我们可以添加偏移量),然后用适当的文本标签替换数字轴标签。
library(ggplot2)
library(reshape2)
library(dplyr)
# Convert data from "wide" to "long" format
CTscores.m = melt(CTscores, id.var="initials")
# Create an offset that we'll use for vertically separating the repeated values
CTscores.m = CTscores.m %>% group_by(variable, value) %>%
mutate(repeats = ifelse(n()>1, 1,0),
offset = ifelse(repeats==0, 0, seq(-n()/25, n()/25, length.out=n())))
ggplot(CTscores.m, aes(label=initials, x=value, y=as.numeric(variable) + offset,
color=initials)) +
geom_text() +
scale_y_continuous(labels=sort(unique(CTscores.m$variable))) +
theme_bw(base_size=15) +
labs(y="", x="") +
guides(color=FALSE)
为了完整起见,以下是如何为重复值创建带有抖动的图形,而不是使用特定的偏移量:
# Convert data from "wide" to "long" format
CTscores.m = melt(CTscores, id.var="initials")
# Mark repeated values (so we can selectively jitter them later)
CTscores.m = CTscores.m %>% group_by(variable, value) %>%
mutate(repeats = ifelse(n()>1, 1,0))
# Jitter only the points with repeated values
set.seed(13)
ggplot() +
geom_text(data=CTscores.m[CTscores.m$repeats==1,],
aes(label=initials, x=value, y=variable, color=initials),
position=position_jitter(height=0.25, width=0)) +
geom_text(data=CTscores.m[CTscores.m$repeats==0,],
aes(label=initials, x=value, y=variable, color=initials)) +
theme_bw(base_size=15) +
guides(color=FALSE)