1

I have to sort alphabetically the name of the species that appear in the data frame, but in turn, they have to be ordered by the category assigned in the "Vuln" column. In my code, the first part is resolved, but I can not group the appearance of the species in the figure by its category.

I tried that ggplot used the order of the data frame data, but I did not get it. My knowledge about R is limited by the little time I have been using it, basically I learn based on trial and error.

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))

I attach the file with the data in .csv format "delimited by commas" https://drive.google.com/open?id=1cOZv39XkxuM64LLXYiLTd_ujUSKeRnPL

enter image description here

Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • Not exactly what you're asking for but might be useful https://stackoverflow.com/a/52214383/786542 – Tung Sep 08 '18 at 17:22
  • Thanks for the thread, it is a possible option. Although the possibility of grouping the data of a matrix by several variables is what it was trying to achieve. Thanks for helping! – Joan Nicolau Jimenez Osuna Sep 11 '18 at 13:55

1 Answers1

1

If I understand you correctly, you want to order your Specie first according to Vuln and within each Vuln according to Specie? If this is the case you can use the following snippet:

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

What the code does is to create a new factor (Specie_ord_vuln_name). In ggplot factors are ordered according to their levels. Thus, you have to assign the levels in the order you want for your plot. We use the order function to get the order of the observation by Vuln and within Vuln by Specie. We use rev to reverse the levels to have them from top to down. Then you can plot it:

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

thothal
  • 16,690
  • 3
  • 36
  • 71