GGPlot Flip This Plot

Viewed 62
library(ggplot2)
library(reshape2)
HAVE = data.frame(VARS = c("cat", "dog", "fox", "rabbit"),
                  "a" = c(1,2,3,4),
                  "b" = c(2,3,1,4),
                  "c" = c(3,1,2,4))

HAVE1 = melt(HAVE, id.vars="VARS")

ggplot(HAVE1, aes(VARS, variable, fill= value)) + 
  geom_tile() +
  scale_fill_gradient(low="white", high="blue")

I wish to produce a color map from yellow (low value) to blue (high value). I wish for the columns on top to be the 'variable' and the yticks to be VARS such as: and please note it is just an example!!

enter image description here


enter image description here

2 Answers

Here's an option with coord_flip to switch the axis and a reordering of the factor levels using fct_rev

ggplot(HAVE1, aes(x = fct_rev(as_factor(VARS)), variable, fill= value)) + 
  geom_tile() +
  scale_fill_gradient(low="yellow", high="blue") +
  coord_flip()

enter image description here

Here's an approach with pivot_longer and scale_x_discrete. Note that tidyr is the successor to reshape2, but is by the same author.

We can re-order the factor levels of VARS to get them to plot in the order you want.

We can also get rid of the axis labels with labs and element_blank.

library(ggplot2)
library(tidyr)
library(dplyr)
HAVE %>% 
  pivot_longer(-VARS,names_to = "variable", values_to = "value") %>%
ggplot(aes(x = variable, y = factor(VARS, rev(levels(VARS))), fill= value)) + 
  geom_tile() +
  scale_fill_gradient(low="yellow", high="blue") +
  scale_x_discrete(position = "top") +
  labs(x = element_blank(), y = element_blank())

enter image description here

If you want the tiles to be square, just add the coord_equal() function:

ggplot(HAVE1,aes(x = variable, y = factor(VARS, rev(levels(VARS))), fill= value)) + 
  geom_tile() +
  scale_fill_gradient(low="yellow", high="blue") +
  scale_x_discrete(position = "top") +
  labs(x = element_blank(), y = element_blank()) + 
  coord_equal()

enter image description here

Related