PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

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

 June 28, 2022     ggplot2, graph, r, rename     No comments   

Issue

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


Solution

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



Answered By - Molx
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing