Home > database >  Ggplot2: Label X-Axis To be What I Want Insted of What It Is
Ggplot2: Label X-Axis To be What I Want Insted of What It Is

Time:02-06

I want the x-axis to be labeled with elements of the lb column from the dataframe df1.

df1 <- read.table(text =
                    "method1  9 0.2402482
                     method2  9 0.1023012
                     method3  8 0.2031448
                     method4 4 0.2654746
                     method5 9 0.4048711")

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

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

Here is what I have is the first image below

What I actually want looks like the second image below

CodePudding user response:

You can use the labels param of the scale_x_discrete() function, like this:

df1 |>
  dplyr::mutate(colour = forcats::fct_reorder(Methods, RMSE)) |>
  ggplot2::ggplot(ggplot2::aes(Methods, RMSE, colour = colour))   
  ggplot2::geom_point(size = 4)   
  ggplot2::geom_segment(aes(Methods, xend = Methods, yend = RMSE, y = 0))   
  ggplot2::scale_color_manual(values = c("green", "yellowgreen", "yellow", "orange", "red"))   
  ggplot2::theme_bw()   labs(color = "Method")   
  ggplot2::scale_x_discrete(labels = function(x) df1[df1$Methods==x, "lb"])

enter image description here

  • Related