如何从图形的整数更改 r 中列的名称

How to change the name of a column in r from an integer for a graph

我正在尝试在 R 中绘制条形图,一周中的几天是 x 轴,我希望它们成为每个条形的标签,但在数据集中,它们从 1 到 7 从开始标记星期天所以我做了以下事情:

week_day2$day_of_week <- recode(week_day2$day_of_week, 
   "1"="Sunday",
   "2"="Monday",
   "3"="Tuesday",
   "4"="Wednesday",
   "5"="Thursday",
   "6"="Friday",
   "7"="Saturday")

但后来我无法按顺序绘制条形图,所以我使用了 forcats 库

library(tidyverse)
library(forcats)

Graph_major_days <- week_day2 %>%
  mutate(name = fct_relevel(day_of_week, 
            "Sunday", "Monday", "Tuesday", 
            "Wednesday", "Thursday", "Friday", 
            "Saturday")) %>%
  ggplot( aes(x=name, y=n)) +
    geom_bar(stat="identity")

我想知道是否有easier/readable方法来做这种事情

如果我没理解错的话,你应该将数字保留在数据集中,而只是将绘图的标签更改为工作日。这是一个完整的例子:

library(ggplot2)
set.seed(0)

df <- data.frame(day_of_week = sample(1:7, 7), n = rnorm(7))
days = c("Sun", "Mon", "Tue", "Thu", "Wed", "Fri", "Sat")

ggplot(df, aes(x = day_of_week, y = n)) + 
  geom_bar(stat="identity") +
  scale_x_continuous(breaks = 1:7, labels = days)

如您所见,即使日期在数据集中没有排序,但它们在图中似乎是有序的。如果需要,您还可以将星期几添加到数据集中,只是不要删除数值。