通过ggplot中的第三个变量对散点图进行排序

Sorting a scatterplot by a third variable in ggplot

这是数据的子集。

structure(list(Transmitter = c(1675L, 1675L, 1675L, 1675L, 1681L, 
1681L, 1681L, 1681L, 1685L, 1685L, 1685L, 1685L, 1685L, 9782L, 
9782L, 9782L, 24166L, 24166L, 24166L, 24166L, 24184L, 24184L, 
24184L, 24184L), Date = structure(c(17392, 17721, 17722, 17393, 
17734, 17729, 17391, 17717, 17392, 17390, 17391, 17381, 17382, 
18079, 18110, 17762, 17751, 18097, 18090, 18091, 18097, 18068, 
18082, 18088), class = "Date"), Year = c(2017L, 2018L, 2018L, 
2017L, 2018L, 2018L, 2017L, 2018L, 2017L, 2017L, 2017L, 2017L, 
2017L, 2019L, 2019L, 2018L, 2018L, 2019L, 2019L, 2019L, 2019L, 
2019L, 2019L, 2019L), DirectionGroups = structure(c(3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 1L, 1L, 1L, 1L), .Label = c("Both", "Marine", "River"), class = "factor")), row.names = c(355L, 
356L, 357L, 358L, 475L, 476L, 477L, 478L, 530L, 531L, 532L, 533L, 
534L, 573L, 574L, 575L, 626L, 627L, 628L, 629L, 764L, 765L, 766L, 
767L), class = "data.frame")

我正在尝试创建随时间变化的单独标记动物的散点图。点按我放入的组着色。目前散点图按发射器的级别排序。相反,我想要一种按 DirectionGroup 对这些数据进行排序的方法。

这是我当前的散点图。

ggplot(data = AbPlot3, aes(x = Date, y = factor(Transmitter), color = DirectionGroups)) + geom_point()+theme_bw()+ylab("Transmitter")+
  scale_color_manual(values = c('grey40', 'black', 'grey70'), labels = c('Transient', 'External', 'Resident'))+
  theme(axis.text.y = element_blank(), axis.title = element_text(size = 16),
        axis.text.x = element_text(size = 14), legend.text = element_text(size = 14),
        legend.title = element_text(size = 16))

本质上,我想要一个地块,所有瞬态点彼此相邻,所有外部点在一起,所有常驻点在一起。

试试这个。正如评论中已经指出的那样,只需按 DirectionsGroup 对数据进行排序,然后将 Transmitter 转换为一个因子并相应地设置顺序,例如通过使用 forcats::fct_inorder:

library(ggplot2)
library(dplyr)

AbPlot3 <- AbPlot3 %>% 
  # Sort data in the wanted order
  arrange(DirectionGroups, Transmitter) %>%
  # Convert to factor and set order according to the order in the df
  mutate(Transmitter = forcats::fct_inorder(factor(Transmitter)))

ggplot(data = AbPlot3, aes(x = Date, y = Transmitter, color = DirectionGroups)) + geom_point()+theme_bw()+ylab("Transmitter")+
  scale_color_manual(values = c('grey40', 'black', 'grey70'), labels = c('Transient', 'External', 'Resident'))+
  theme(axis.text.y = element_blank(), axis.title = element_text(size = 16),
        axis.text.x = element_text(size = 14), legend.text = element_text(size = 14),
        legend.title = element_text(size = 16))

reprex package (v0.3.0)

于 2020 年 6 月 11 日创建