简体   繁体   中英

How to re-arrange the boxplots in r

My data look like this. I used melt function to arrange data like this

                Legend     variable   value
1             Grassland         NDVI   0.139
2             Grassland         NDVI   0.285
3             Grassland         NDVI   0.134
4             Grassland         NDVI   0.243
5             Grassland         NDVI   0.113
6             Grassland         NDVI   0.144
7             Grassland         NDVI   0.212
8             Grassland         NDVI   0.249
9             Grassland         NDVI   0.231
10            Grassland         NDVI   0.192
11            Grassland         NDVI   0.159
12            Grassland         NDVI   0.146
13            Grassland         NDVI   0.177
14            Grassland         NDVI   0.287
15            Grassland         NDVI   0.240
16            Grassland         NDVI   0.285

There are four legends*( Grassland, Shrubby patches, Non-vegetative area and forest area and five variables in each legend ie categories*. I got my ggplot as 我的ggplot

I dont like the way legends are ordered in each variable. How do I change the order? I would like to have Non-vegetative area at first, then grassland, shrubby pathches and at last the forest area.

You can use factor , explicitly setting the order of the levels argument.

As a baseline:

library(ggplot2)
ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot()

<code> iris $ Species </ code>,默认顺序

df <- iris
levels(df$Species)
# [1] "setosa"     "versicolor" "virginica" 
df$Species <- factor(df$Species, levels = levels(df$Species)[c(3,1,2)])
ggplot(df, aes(Species, Sepal.Length)) + geom_boxplot()

<code> iris $ Species </ code>,已重新排序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM