R语言 Ggplot2:将X轴标记为我想要的,而不是它本身

gk7wooem  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(156)

我希望使用 Dataframe df1lb列的元素标记x-axis

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

这是我得到的

我真正想要的看起来像

vsnjm48y

vsnjm48y1#

可以使用scale_x_discrete()函数的labels参数,如下所示:

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"])

相关问题