我有以下数据集:
Location Type FromDate ToDate 1 2 3 4 5
A 1 12-Jul 13-Jul 2 4 0 1 2
A 2 12-Jul 13-Jul 0 0 1 4 1
B 1 12-Jul 13-Jul 0 1 1 3 1
B 2 12-Jul 13-Jul 1 0 0 0 1
C 1 12-Jul 13-Jul 2 3 1 5 0
C 2 12-Jul 13-Jul 3 3 1 0 0
如何在 R 中为第 1 天到第 5 天的每个位置(包括类型 1 和类型 2)创建条形图?
最佳答案
一个稍微替代的解决方案,它不使用 reshape2
和 plyr
,而是使用 dplyr
和 tidyr
。后一种组合使用了越来越流行的管道。
首先读取数据:
df <- read.table(header=TRUE, text="Location Type FromDate ToDate 1 2 3 4 5
A 1 12-Jul 13-Jul 2 4 0 1 2
A 2 12-Jul 13-Jul 0 0 1 4 1
B 1 12-Jul 13-Jul 0 1 1 3 1
B 2 12-Jul 13-Jul 1 0 0 0 1
C 1 12-Jul 13-Jul 2 3 1 5 0
C 2 12-Jul 13-Jul 3 3 1 0 0")
# remove the X-es which are put in front of the days
names(df) <- gsub("X","",names(df))
加载所需的库:
library(dplyr)
library(tidyr)
library(ggplot2)
将数据从宽格式融合为长格式:
df.m <- df %>% gather(day,value,5:9)
创建情节:
ggplot(data=df.m, aes(x=day, y=value, fill=as.factor(Type))) +
geom_bar(stat="identity", position="dodge") +
xlab("Day of the week") +
scale_fill_discrete("Type\nof\nsomething\n") +
facet_grid(Location ~ ., labeller=label_both) +
theme_bw() +
theme(axis.title.y=element_blank())
结果是:
<小时/>但是,考虑到您的数据,折线图可能是更好的可视化效果:
ggplot(data=df.m, aes(x=day, y=value, color=as.factor(Type), group=as.factor(Type))) +
geom_line(size=1.5) +
xlab("Days") +
scale_color_discrete("Type\nof\nsomething\n") +
facet_grid(Location ~ ., labeller=label_both) +
theme_bw() +
theme(axis.title.y=element_blank())
结果是:
关于mysql - 从多列创建条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25730912/