LivingstoneM
LivingstoneM

Reputation: 1088

Plot Trends of data over a period of time

I am new to R and I would like to generate data trends of hospital data that I have. Now this is how the data looks like

df <- data.frame("Hospital" = c("Buge Hosp", "Buge Hosp", "Greta Hospital", "Greta Hospital",
                               "Makor Hosp", "Makor Hospital"),
                 "Period" = c("Jul-18","Aug-18", "Jul-18","Aug-18", "Jul-18","Aug-18"),
                 "Medical admission" = c(12,56,0,40,5,56),
                 "Surgical admissions" = c(10,2,0,50,20,56),
                 "inpatient admissions" = c(9,5,6,0,60,96))
df

I would like to generate data trends based on the monthly period as given in the data for each individual hospital. Anyone with an Idea on how I can do this using R I will deeply appreciate

Upvotes: 0

Views: 172

Answers (1)

Cliff Bueno
Cliff Bueno

Reputation: 96

You may want to provide a bit more detail about what you are looking for. But here is a quick way to manipulate the data and make a graph with the ggplot2 package.

# Libraries
library(ggplot2)
library(reshape2)

# Data
df <- data.frame("Hospital" = c("Buge Hospital", "Buge Hospital", "Greta Hospital", "Greta Hospital",
                                "Makor Hospital", "Makor Hospital"),
                 "Period" = c("Jul-18","Aug-18", "Jul-18","Aug-18", "Jul-18","Aug-18"),
                 "Medical admissions" = c(12,56,0,40,5,56),
                 "Surgical admissions" = c(10,2,0,50,20,56),
                 "Inpatient admissions" = c(9,5,6,0,60,96))
df
# Note, generally it's good not to have spaces in column names. But fyi, R will put a period where the space is.
# I also changed the hospital names to be consistent

# Melt data into long format
df_long <- melt(data = df,
                id.vars = c("Hospital","Period"), 
                measure.vars = c("Medical.admissions", "Surgical.admissions", "Inpatient.admissions"))

# Plot with color as admission type and different panel for each hospital 
ggplot(df_long, aes(x = Period, y = value, 
                    colour = variable, group = variable)) +
  geom_point() +
  geom_line() +
  scale_x_discrete(limits = rev(levels(df_long$Period))) +
  labs(x = "Month", y = "Number of People", colour = "Type") +
  facet_wrap(~ Hospital)

# Stacked barplot
ggplot(df_long, aes(x = Period, y = value, 
                    fill = variable, group = variable)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(limits = rev(levels(df_long$Period))) +
  labs(x = "Month", y = "Number of People", fill = "Type") +
  facet_wrap(~ Hospital)

# Dodged barplot
ggplot(df_long, aes(x = Period, y = value, 
                    fill = variable, group = variable)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_x_discrete(limits = rev(levels(df_long$Period))) +
  labs(x = "Month", y = "Number of People", fill = "Type") +
  facet_wrap(~ Hospital)

Upvotes: 2

Related Questions