Search code examples
rggplot2colorbar

ggplot - plot only the colourbar


I wish to plot only the colourbar, if possible at the center of the window, like this :

enter image description here

One example where I can't remove the points, axis and background.

library("ggplot2")
library("viridis")    

df <- data.frame(x = c(1,2,3,4,5,6), y = c(7,4,9,2,6,7))

ggplot(data = df, aes(x = x, y = y, colour = y)) + 
  geom_point() +
  scale_color_viridis()

Solution

  • The package ggpubr has a function for exactly this need.

    df <- data.frame(x = c(1,2,3,4,5,6), y = c(7,4,9,2,6,7))
    
    p <- ggplot(data = df, aes(x = x, y = y, colour = y)) + 
      geom_point() +
      scale_color_viridis() +
      theme_minimal()
    
    # ggpubr does this for you
    library(ggpubr)
    leg <- get_legend(p)
    as_ggplot(leg)
    

    enter image description here