Home > Software engineering >  Lollipop Plot: Customize Colours According to a Variable and the Lollipop Height According to Anothe
Lollipop Plot: Customize Colours According to a Variable and the Lollipop Height According to Anothe

Time:04-16

I have the below data frame to demonstrate what I want.

library(ggplot2)

df1 <- data.frame(Methods = c('b', 'a', 'c', 'd', 'e'), lb = c(9, 7, 9, 4, 9), RMSE = c(0.26177952, 0.11294586, 0.02452239, 0.08290467, 0.41488542))

df1

  Methods lb       RMSE
1       b  9 0.26177952
2       a  7 0.11294586
3       c  9 0.02452239
4       d  4 0.08290467
5       e  9 0.41488542

An answer make the below output of the R code above:

The lollipop plot simply reveals one thing which is the height of RMSE.

What I Want

  1. In addition to the height of the RMSE, I want the colour to show the distribution of the lb column.

  2. In the case of item 1 above, the lb variable (9, 7, 9, 4, 9) and values of lb should be attached to the chart legend.

  3. I want the minimum value of the lb variable to carry green the next minimum to carry yellowgreen, the middle value to carry yellow, the penultimate maximum to carry orangeand the maximum value of thelbvariable to carryred`.

  4. If two methods have the same value of lb, give them the same colour then continue to the next value of lb with the next colour.

The above is what I have summarized in the below picture:

CodePudding user response:

I am not sure if this is what you want, but you can use the following code:

library(tidyverse)
df1 %>%
  mutate(lb = as.factor(lb)) %>%
  ggplot(aes(x = Methods, y = RMSE, colour = lb))   
  geom_point(size = 4)   
  geom_segment(aes(x = Methods, xend = Methods, yend = RMSE, y = 0))   
  scale_color_manual(values = c("green", "yellow", "red"))   
  theme_bw()

Output:

enter image description here

CodePudding user response:

along these lines?

df1 |>
ggplot(aes(x = Methods, 
           xend = Methods,
           y = RMSE,
           yend = 0,
           col = cut(lb, 5, labels = c('XS','S','M','L','XL'))
           )
       )  
geom_point(pch = 20, size = 4) 
geom_segment()  
scale_color_manual(values = c(XS = 'green', S = 'yellowgreen', 
                              M = 'yellow', L = 'orange', XL = 'red'))

edit: in case of tied lb levels, you could add a ranked lb and use it for colouring like so:


df1 |>
mutate(lb_rank = rank(lb)) |>
ggplot(aes(x = Methods, 
           xend = Methods,
           y = RMSE,
           yend = 0,
           col = cut(lb_rank, 5,
                      labels = c('XS','S','M','L','XL'))
           )
       ) ## ... remaining stuff
  • Related