Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

r - Re-ordering ggplot according to categorical variable

I am currently using ggplot in R to visualise some rock art data I am working on. My plot shows individual rock art sites (listed with their individual ID, here called SCRAP ID) on the Y-Axis. On the X-Axis, we have the different slope classes (5 classes in total): Flat/Gentle, Soft/Smooth, Medium, Accentuated, Very Accentuated). This is my plot.

I want to show the type of slope class at each individual site, but order the SCRAP ID according to the slope class, e.g. the slope class with the lowest frequency occurs on the top and the slope class with the highest frequency on the bottom. I haven't been successful to fix this and welcome any pointers/help! Or suggestions on better ways to visualise this information.

Here is my code:

### Import data
menteith_reclass <- read_csv("Menteith/CSV/Menteith_slope_percentage_reclass.csv")

### Transform ID from numeric to factor
menteith_reclass$SCRAP_ID <- as.factor(menteith_reclass$SCRAP_ID)   

### Transform slope class from character to factor
menteith_reclass$`SLOPE RECLASS 2` <- factor(menteith_reclass$`SLOPE RECLASS 2`, levels = c("Flat/Gentle", "Soft/Smooth", "Medium", 
            "Accentuated", "Very Accentuated"))

### Visualise the data as histogram
menteith_slope <- ggplot(menteith_reclass)+
geom_bar(aes(x=SCRAP_ID, y=`SLOPE RECLASS 2`, fill=`SLOPE RECLASS 2`), stat = "identity")+
  coord_flip()+
   theme(plot.title.position="plot",text = element_text(size=5))+
  scale_fill_manual(name="Slope reclassified",labels =c("Soft/Smooth (2-5%)", "Medium (5-15%)", "Accentuated (15-40%)"), values=c( "#dfc27d","#80cdc1", "#018571"))+
xlab("SCRAP ID") + ylab("")+
    ggtitle("Terrain slope values for rock art sites in Port of Menteith",  subtitle = "Reclassified according to Butzer (1982)")

plot(menteith_slope)

question from:https://stackoverflow.com/questions/65881830/re-ordering-ggplot-according-to-categorical-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like you can reorder SCRAP_ID like this in ggplot:

aes(x=reorder(SCRAP_ID, `SLOPE RECLASS 2`), y=`SLOPE RECLASS 2`, fill=`SLOPE RECLASS 2`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...