按类别分组并使用ggplot按字母顺序排序

时间:2018-09-08 08:21:37

标签: r ggplot2

我必须按字母顺序对出现在数据框中的物种的名称进行排序,但又必须按“漏洞”(Vuln)列中分配的类别对其进行排序。在我的代码中,第一部分已解决,但我无法按图中的类别将物种的外观分组。

我尝试过ggplot使用数据帧数据的顺序,但是我没有得到它。我对R的了解受到我使用它的很少时间的限制,基本上我是根据反复试验来学习的。

df1 <- read.csv(file=paste(di,"/specieorder.csv", sep=""), header=TRUE, sep=";")

# Change order (allphabetically) to improve the plot
df1 <- within(df1, Specie_ord <- ordered(Specie, levels=rev(sort(unique(Specie)))))
df1<- df1[df1$Group.1!=' ', ]

str(df1)
df1$Zone <- as.factor(df1$Zone)

library(ggplot2)

p <- ggplot(df1, aes(Zone,Specie_ord)) + 
  geom_point(aes(size=x), shape=15, col='darkred') + 
  scale_size('Number\nof\nRecords')+
  theme_bw() +facet_grid(.~Fire) +
  xlab('Zone') + ylab('Species')
p + ggtitle("Abundance by species") + 
  theme(plot.title = element_text(face="bold", size=12))

我将文件与.csv格式的数据附加“用逗号分隔” https://drive.google.com/open?id=1cOZv39XkxuM64LLXYiLTd_ujUSKeRnPL

enter image description here

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,是要先根据SpecieVuln进行排序,还是要根据Vuln对每个Specie进行排序?在这种情况下,您可以使用以下代码段:

df1$Specie_ord_vuln_name <- factor(df1$Specie,
                                   rev(unique(df1$Specie[order(df1$Vuln, df1$Specie)])))

代码要做的是创建一个新因子(Specie_ord_vuln_name)。在ggplot中,因子是根据其级别排序的。因此,您必须按照想要的绘图顺序分配级别。我们使用order函数通过Vuln获取观测的顺序,并在Vuln内获取Specie的观测顺序。我们使用rev来反转级别,以使它们从上到下。然后可以绘制它:

ggplot(df1, aes(Zone, Specie_ord_vuln_name)) + 
   geom_point(aes(size = x), shape = 15, col = 'darkred') + 
   scale_size('Number\nof\nRecords')+
   theme_bw() + facet_grid(.~Fire) +
   xlab('Zone') + ylab('Species') +
   ggtitle("Abundance by species") + 
   theme(plot.title = element_text(face = "bold", size = 12))

enter image description here

相关问题