Home > Back-end >  geom_bar combine 2 dataset onto one graph
geom_bar combine 2 dataset onto one graph

Time:11-21

I have two dataframes with paired scores, each scoring patients on a 1-8 scoring system (Where 1= managing well and 8 = terminally ill). One score is done by the patient and one by the clinician.

sample data

df <- data.frame(Patient = c(1,1,2,4,5,3,2,6,7,6,3,4,2,3,5,6,7,3,8,1), Clinican= c(1,2,2,5,4,5,4,4,4,2,3,5,4,6,5,4,3,7,7,1))

I'd like to create a bar chart similar to the one below using my dataset. enter image description here

Any help would be much appreciated. I believe I need dplyr pivot_longer similar to this post: enter image description here

CodePudding user response:

Here is a solution using pivot_longer and geom_bar as you asked.

Libraries

library(dplyr)
library(tidyr)
library(ggplot2)

Solution

You can change name and value for whatever name you prefer.

Also, the x-axis is categorical, so we have to mutate it to factor.

You can then recode the factor value for the labels you need (e.g., 'well', 'very fit'...)

df %>% 
  pivot_longer(Patient:Clinican, names_to = "name", values_to = "value") %>% 
  mutate(value = factor(value)) %>% 
  ggplot(aes(x = value, fill = name))  
  geom_bar(position = "dodge")

Output

enter image description here

  • Related