Reputation: 330
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()
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 year
s.
Problem: because I also want legend to be factor, not continuous. This creates problem in ordering.
Ideal order:
Upvotes: 0
Views: 764
Reputation: 4524
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()
Upvotes: 1