0

I am practising R with open datasets, I gone through some questions online and see the following code can customise the order in legend, but it didn't work for me:

dataframe$column<-factor(dataframe$column, levels=c("b","g","e","y","k"))

So in this case, I want my order be: b,g,e,y,k instead of alphabetical order as default.

Here is the dataset:

mass<-c(0.187,0.257,0.237,0.064,0.047,0.191,0.080,0.155,0.229,0.258)
species<-c("B. constrictor", "B. constrictor", "B. constrictor", "M. nauta", 
"M. nauta","M. spilota","M. spilota","M. viridis","B. irregularis","B. 
irregularis")
mean<-c(11.02,17.05,12.80,1.53,0.78,6.52,1.66,5.93,10.37,11.67)
snake_info<-data.frame(species,mass,mean)

Here is my code I wrote:

snake_info$species<-factor(snake_info$species, 
levels=c("B.constrictor","M.nauta","M.spilota","M.viridis","B.irregularis"))
base_1a<-ggplot(snake_info, aes(x=mass, y=mean))+
geom_point(aes(shape=factor(species)))+
scale_shape_manual(values=c(1,15,17,25,2)) +
labs(x=expression(paste("mass"," ","(kg)")),y=expression(paste("total"," ",italic("F"),""[obs]," 
",italic("(N)"))))+
geom_smooth(method="lm", se = FALSE, col="black")+
theme_classic()

Unfortunately this is what I get - the order of legend is arranged alphabetically. Graph

Any help would be appreciated!!!

ivanllam
  • 3
  • 2

1 Answers1

0

The levels should match exactly with the species names present in the dataset. Here is the solution

library(tidyverse)

snake_info %>% 
  mutate(species=factor(species, levels=c("B. constrictor","M. nauta","M. spilota","M. viridis","B. irregularis"))) %>% 
           ggplot(aes(x=mass, y=mean), show.legend=FALSE) +
           geom_point(aes(shape=species)) +
           scale_shape_manual(values=c(1,15,17,25,2)) +
           labs(x=expression(paste("mass"," ","(kg)")),
           y=expression(paste("total"," ",italic("F"),""[obs]," ",italic("(N)"))))+
           geom_smooth(method="lm", se = FALSE, col="black") +
           theme_classic()

enter image description here

UseR10085
  • 7,120
  • 3
  • 24
  • 54
  • Thank you!!! It works for me. I will try to figure out what's wrong with my code. – ivanllam Jul 15 '20 at 08:00
  • You have not provided space in `"B.constrictor", "M.nauta", "M.spilota", "M.viridis", "B.irregularis"` within `levels` function, but you data contains spaces between genus and species names like `"B. constrictor", "B. constrictor", ...`. As these two were not matching, the plot was coming empty. – UseR10085 Jul 15 '20 at 08:04