Home > database >  Lollipop Chart: Assign Colours According to the Ascending Values of a Column Name Using R
Lollipop Chart: Assign Colours According to the Ascending Values of a Column Name Using R

Time:06-03

I have a column (RMSE) in a data frame in which I want the colour (green, yellowgreen, yellow, orange, red) of a lollipop chart to vary according to the values of the column RMSE. I want the pop representing the lowest to be green while the pop representing the highest RMSE value to be `red

    df1 <- read.table(text =
                    "nbb_RMSE  9 0.2402482
                     mbb_RMSE  9 0.1023012
                     cbb_RMSE  8 0.2031448
                     tmbb_RMSE 4 0.2654746
                     tcbb_RMSE 9 0.4048711")

colnames(df1) <- c("Methods", "lb", "RMSE")

df1 |>
  dplyr::mutate(lb = as.factor(lb)) |>
  ggplot2::ggplot(ggplot2::aes(x = Methods, y = RMSE, colour = Methods))   
  ggplot2::geom_point(size = 4)   
  ggplot2::geom_segment(ggplot2::aes(x = Methods, xend = Methods, yend = RMSE, y = 0))   
  ggplot2::scale_color_manual(values = c("green", "yellowgreen", "yellow", "orange", "red"))   
  ggplot2::theme_bw()

This is what I get

CodePudding user response:

Similar approach to @stephan's option:

library(tidyverse)

df1 <- read.table(text =
                    "nbb_RMSE  9 0.2402482
                     mbb_RMSE  9 0.1023012
                     cbb_RMSE  8 0.2031448
                     tmbb_RMSE 4 0.2654746
                     tcbb_RMSE 9 0.4048711")

colnames(df1) <- c("Methods", "lb", "RMSE")

df1 |>
  mutate(colour = fct_reorder(Methods, RMSE)) |>
  ggplot(aes(Methods, RMSE, colour = colour))   
  geom_point(size = 4)   
  geom_segment(aes(Methods, xend = Methods, yend = RMSE, y = 0))   
  scale_color_manual(values = c("green", "yellowgreen", "yellow", "orange", "red"))   
  theme_bw()

Created on 2022-06-02 by the reprex package (v2.0.1)

CodePudding user response:

One option would be to use a named color vector where you use reorder to assign the names according to the value of RMSE:

library(ggplot2)

pal <- c("green", "yellowgreen", "yellow", "orange", "red")
names(pal) <- levels(reorder(df1$Methods, df1$RMSE))

df1 |>
  dplyr::mutate(lb = as.factor(lb)) |>
  ggplot2::ggplot(ggplot2::aes(x = Methods, y = RMSE, colour = Methods))   
  ggplot2::geom_point(size = 4)   
  ggplot2::geom_segment(ggplot2::aes(x = Methods, xend = Methods, yend = RMSE, y = 0))   
  ggplot2::scale_color_manual(values = pal)   
  ggplot2::theme_bw()

  • Related