我是R的新手,我想生成我拥有的医院数据的数据趋势。现在数据看起来是这样的
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我希望根据每个医院的数据中给出的月度周期来生成数据趋势。任何人如果有关于如何使用R来做这件事的想法,我将非常感谢
发布于 2020-04-10 15:06:41
您可能希望提供有关您正在寻找的内容的更多细节。但这里有一种使用ggplot2包操作数据和绘制图形的快速方法。
# 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)https://stackoverflow.com/questions/61135157
复制相似问题