Home > Net >  Reorder heatmap by specific group in R
Reorder heatmap by specific group in R

Time:05-04

Using the airline-safety dataset available enter image description here

but this orders the heatmap by value, regardless of what the group is i.e. incidents, fatal accidents or fatalities.


# load packages -----------
library(tidyverse)
library(ggplot2)
library(reshape2)
library(dplyr)
library(plyr)
library(scales)
library(forcats)

# read in the data
airlines <- read.csv("/Volumes/GoogleDrive/My Drive/Uni/DVN/AT2/Blog 2/airline_incidents.csv", header = TRUE) 

# select relevant columns 
airlines_00_14 <- airlines[,c(1,6,7,8)]

# create a long dataset
airlines_00_14.m <- melt(airlines_00_14) 

# rescale values for heat map 
airlines_00_14.m <- ddply(airlines_00_14.m, .(variable), transform, rescale = rescale(value))

# create heat map 
(q <- airlines_00_14.m %>%
    ggplot( aes(x = variable, y = reorder(airline, value)))   
    geom_tile(aes(fill = rescale), colour = "white")   
    scale_fill_gradient(low = "white", high = "steelblue")) 

CodePudding user response:

One way to do this is to create the order before you melt, like this:

# order by fatalities and generate air_order value
airlines_00_14 = airlines_00_14[order(airlines_00_14$fatal_accidents_00_14),]
airlines_00_14$air_order = seq_len(nrow(airlines_00_14))

Then, when you use reshape2::melt, set `id.vars = c("airline","air_order")

# create a long dataset
airlines_00_14.m <- reshape2::melt(airlines_00_14,id.vars = c("airline", "air_order"))

Then, in your plot, use y=reorder(airline, air_order) instead of the current y=reorder(airline, value)

Output: airlines

  • Related