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

Categories

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

r - Reorder rows according to two column values in geom_tile() heatmap

library(tidyverse)

df <- data.frame(country = c("USA", "USA", "USA", 
                             "UK", "UK", "UK", 
                             "Japan", "Japan", "Japan", 
                             "Germany", "Germany", "Germany",
                             "Sweden","Sweden","Sweden",
                             "Norway","Norway","Norway"),
                 year = c(2000, 2001, 2002, 
                          2000, 2001, 2002, 
                          2000, 2001, 2002, 
                          2000, 2001, 2002, 
                          2000, 2001, 2002, 
                          2000, 2001, 2002),
                 value = c(0,1,1,
                           1,1,1,
                           0,0,0,
                           0,0,1,
                           0,1,1,
                           0,1,0))

ggplot(df, aes(year, country, fill = factor(value)))+
  geom_tile(color = "white", size = 1)+
  theme_minimal() 

Raw Plot

This is the data, code, and raw plot that I get. Is there a way that I can reorder country rows by their value values and year at the same time?

My goal: country rows will be ordered by their first value=1 in years.

Problem: because I also want legend to be factor, not continuous. This creates problem in ordering.

Ideal order:

  • 1st row: UK
  • 2nd row: Sweden or USA (because they have the same values)
  • 3rd row: Sweden or USA (because they have the same values)
  • 4th row: Norway
  • 5th row: Germany
  • 6th row: Japan

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

1 Answer

0 votes
by (71.8m points)

You can use fct_relevel from the package forcats, if this is what you are looking for.

library(tidyverse)

library(forcats)
ro <- c('Japan', 'Germany', 'Norway', 'USA','Sweden', 'UK')

df %>%
  mutate(country= fct_relevel(country, ro)) %>% 
ggplot(aes(year, country, fill = factor(value))) +
  geom_tile(color = "white", size = 1)+
  theme_minimal()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...