从多列创建条形图
问题描述:
我有以下数据集:
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
如何在第 1 天到第 5 天在 R 中为每个位置(包括类型 1 和类型 2)创建条形图?
How can I create a bar graph in R for each location, including both types 1 and 2, during days 1 to 5?
答
你应该更准确地阐明你的问题,以便读者确切地知道你想要什么.还期望您通过解释您已经尝试过的方法来展示解决问题的努力.
You should clarify your questions more precisely, so that readers know exactly what you want. It is also expected that you show an effort in solving the problem by explaining what you already tried.
因此我只能猜测你想要什么,这是我的建议:
I could therefore only guess what you wanted and here is my suggestion:
加载需要的包:
require(ggplot2)
require(reshape2)
require(plyr)
重新创建您的 df:
location = c('A','A','B','B','C','C')
type = rep(c(1,2),3)
fdate = rep('12-Jul', 6)
tdate = rep('13-Jul', 6)
v1 = c(2,0,0,1,2,3)
v2 = c(4,0,1,0,3,3)
v3 = c(0,1,1,0,1,1)
v4 = c(1,4,3,0,5,0)
v5 = c(2,1,1,1,0,0)
dat = data.frame(location, type, fdate, tdate, v1, v2, v3, v4, v5)
重新排列数据以进行绘图:
Rearranging data for plotting:
melted = melt(dat, id.vars=c('location', 'type', 'fdate', 'tdate'))
sums = ddply(melted, c('fdate', 'tdate', 'location', 'type', 'variable'),
summarise, sum=sum(value))
使用 ggplot2 绘图:
Plot with ggplot2:
ggplot(aes(x=variable, y=sum, fill=as.factor(type)), data=sums) +
geom_bar(stat="identity", position="dodge") +
facet_grid(location ~ .)
使用您发布的确切数据框:
# read data
dat2 <- read.table(header=T, 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")
# rearranging data for plotting
melted = melt(dat2, id.vars=c('Location', 'Type', 'FromDate', 'ToDate'))
sums = ddply(melted, c('FromDate', 'ToDate', 'Location', 'Type', 'variable'),
summarise, sum=sum(value))
# plot with ggplot2
ggplot(aes(x=variable, y=sum, fill=as.factor(Type)), data=sums) +
geom_bar(stat="identity", position="dodge") +
facet_grid(Location ~ .)