我有一个像这样的数据集:
df <- data.frame(Species = c("Sp A", "Other sp", "Other sp", "Other sp",
"Sp A", "Other sp", "Other sp"),
Study = c("A", "A", "A", "A",
"B", "B", "B"),
Value = c(1, 3, 4, 5, 3, 6, 7))
看起来像这样:
> df
Species Study Value
1 Sp A A 1
2 Other sp A 3
3 Other sp A 4
4 Other sp A 5
5 Sp A B 3
6 Other sp B 6
7 Other sp B 7
我想将物种A的值与同一研究中其他物种的值进行比较 这是我现在的情节:
ggplot(df, aes(y = Value, x = Species)) +
geom_point(shape = 1) +
geom_line(aes(group = Study), color = "gray50") +
theme_bw()
我不想要垂直线条。取而代之的是,我希望有5条线,3条从较低的“Sp A”点开始,朝向3条相应的“其他sp”点从同一研究(A)开始,2条从上部“Sp A”开始朝向来自同一研究的其他两点(B)。
答案 0 :(得分:4)
可能有一种更优雅的方式,但这是一个有效的解决方案。诀窍是稍微重新排列数据,然后使用geom_segment
:
library(tidyverse)
df <- data.frame(Species = c("Sp A", "Other sp", "Other sp", "Other sp",
"Sp A", "Other sp", "Other sp"),
Study = c("A", "A", "A", "A",
"B", "B", "B"),
Value = c(1, 3, 4, 5, 3, 6, 7))
# Split data
other <- df %>% filter(Species == "Other sp")
sp_a <- df %>% filter(Species == "Sp A")
# Recombine into the data set for plotting
df <- other %>%
inner_join(sp_a, by = "Study")
# Make the plot
ggplot(df, aes(x = Species.y, y = Value.y)) +
geom_segment(aes(xend = Species.x, yend = Value.x, colour = Study))
根据需要调整图表!
答案 1 :(得分:2)
如果对于geom_line
的每个级别,您复制Study
行的数量以匹配Sp A
行的数量,然后分配,则可以使用Other sp
执行此操作Sp A
美学的每对Other Sp
和group
的唯一ID。
library(tidyverse)
df %>% group_by(Study) %>%
slice(c(rep(1,length(Species[Species=="Other sp"])),2:n())) %>%
group_by(Study, Species) %>%
mutate(ID = paste0(Study, 1:n())) %>%
ggplot(aes(y = Value, x=Species, group=ID, colour=Study)) +
geom_point(shape=1) +
geom_line() +
theme_bw()