Xavier Xavier - 9 months ago 32
R Question

How to reorder bars of a tornado graph in R?

I am trying to plot a tornado graph for sensitivity analysis purposes. This is what I have so far.

# Install Required Package
list.of.packages <- c("ggplot2")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[, "Package"])]
if (length(new.packages)) install.packages(new.packages)

library("ggplot2")

OP <- par(mar = c(7,7,7,7))

data <- matrix(c(-0.10,0.15,-0.01,0.01,-0.03,0.08,-0.1,0.07), ncol = 4)

# Amount of Change in Variables
rownames(data) <- c('+25%','-25%')

# Names of Variables
colnames(data) <- c('Variable 1', 'Variable 2', 'Variable 3','Variable 4')

# For Plotting % on X-Axis
x <- seq(-0.30,0.30, length=13)

SEQUENTIAL <- brewer.pal(4, "YlOrRd")

barplot(data[1,], main="Tornado Graph", horiz = T, las=1, xlim = c(-0.30,0.30), xaxt='n', ylab = '', col=SEQUENTIAL)
barplot(data[2,], horiz = T, las=1, xlim = c(-0.30,0.30), xaxt='n', ylab = '', col=SEQUENTIAL, add = TRUE)

# Add x-axis
axis(1, at=x, labels=paste0(x * 100," %"), las=TRUE)

par(OP)


The bars of the tornado graph are not sorted like in a proper graph. How do I sort them in decreasing length?

Thanks

G5W G5W
Answer Source

Just put the columns in order for plotting. Replace your two barplot statements with

ORD = order(data[2,] - data[1,])
barplot(data[1,ORD], main="Tornado Graph", horiz = T, las=1, 
       xlim = c(-0.30,0.30), xaxt='n', ylab = '', col=SEQUENTIAL)
barplot(data[2,ORD], horiz = T, las=1, xlim = c(-0.30,0.30), xaxt='n', 
       ylab = '', col=SEQUENTIAL, add = TRUE)

enter image description here