Home > Software design >  How to change the name of a column in r from an integer for a graph
How to change the name of a column in r from an integer for a graph

Time:11-26

I'm trying to do a bar plot in R the days of the week are the x axis, and I want them to be the labels for each bar but in the dataset they are marked from 1 to 7 starting from Sunday so I did the following:

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

But then I couldn't make the bar plot in order so I used forcats library

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

I want to know if there is an easier/readable way to do this kind of thing

CodePudding user response:

If I understood you correctly, you should keep the numbers in the dataset and just change the labels of the plot to the weekdays instead. Here's a complete example:

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)

As you can see, even though the days are not ordered in the dataset they appear ordered in the plot. If you need to you can also add the days of the week to the dataset, just don't remove the numeric values.

enter image description here

  • Related