Home > database >  Hack Legend Key for Lollipop Chart in R
Hack Legend Key for Lollipop Chart in R

Time:06-03

I want to replace the element of a column with the element of another column in ggplot2

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()

Here is its output

What I Want

The lb column should be arranged as follows: Green which represents the smallest RMSE corresponds to 9 in lb column, yellowgreen which represent the nest high value in RMSE corresponds to 8 in lb column,yellow which represent the nest high value in RMSE corresponds to 9 in lb column, orange which represent the nest high value in RMSE corresponds to 4 in lb column,red which represent the nest high value in RMSE corresponds to 9 in lb column.

I want the label color on the legend to change to the name of a column called lb in the dataframe.

Here is what I want

CodePudding user response:

You can use the name and labels arguments in scale_color_manual

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"),
                     labels = c(9, 8, 9, 9, 4), name = "lb")   
  theme_bw(base_size = 16)

enter image description here

  • Related