每个因子R的自动历史记录

时间:2018-07-12 08:57:16

标签: r render

我有此数据:

> dput(data)
structure(list(Location = c("a", "b", "c", "d"), duration.hours.mean_2006 = c(14.0623159303882, 
12.4725490196078, 7.03333333333333, 34.5672181372549), duration.hours.mean_2007 = c(13.0378277153558, 
9.99890350877193, 9.63827160493827, 33.0019047619048), duration.hours.mean_2008 = c(12.9337023370234, 
12.6810699588477, 11.2606060606061, 34.5296875), duration.hours.mean_2009 = c(12.5025960539979, 
10.9380407124682, 11.7544715447154, 34.1690476190476), duration.hours.mean_2014 = c(95.175, 
95.175, 95.175, 95.175)), .Names = c("Location", "duration.hours.mean_2006", 
"duration.hours.mean_2007", "duration.hours.mean_2008", "duration.hours.mean_2009", 
"duration.hours.mean_2014"), row.names = c(NA, -4L), class = "data.frame")

我想为每个“位置”因子绘制直方图:一个代表a,另一个代表b,另一个代表c,依此类推。因此在X轴上,我将具有duration.hours.mean_2006,duration .hours.mean_2007,等等。

是否可以自动执行类似的操作?建立历史记录不是问题,循环是问题。我暂时无法在互联网上找到相关的问题/文章!

2 个答案:

答案 0 :(得分:1)

library(tidyr)    
test <- gather(df, key = "year", value = "duration_value_mean", 2:6)
ggplot(test, aes(x = duration_value_mean)) + geom_histogram(binwidth = 1) + facet_wrap(~ Location)

image

答案 1 :(得分:0)

我不明白您打算如何在每个位置和每个持续时间使用直方图,因为每个都只有一个值而不是数据分布。但是,您可以从这些数据中得到的是: enter image description here

library(ggplot2)
test<-reshape2::melt(df,"Location")
ggplot(test,aes(variable,value,fill=Location))+geom_col()+coord_flip()

对于同一面板上每个位置的单独图:

ggplot(test,aes(variable,value,fill=Location))+geom_col()+coord_flip()+
  facet_wrap(~ Location)

enter image description here 或者,您可以按位置对数据进行子集,然后绘制。

library(dplyr)
a<-test %>%
  filter(Location=="a")
b<-test %>%
  filter(Location=="b")
c<-test %>%
  filter(Location=="c")
d<-test %>%
  filter(Location=="d")

p1<-ggplot(a,aes(variable,value))+geom_col(fill="red")+coord_flip()#Plot for 'a' Location
p2<-ggplot(b,aes(variable,value))+geom_col(fill="green")+coord_flip()#Plot for 'b' Location
p3<-ggplot(c,aes(variable,value))+geom_col(fill="blue")+coord_flip()#Plot for 'c' Location
p4<-ggplot(d,aes(variable,value))+geom_col(fill="grey")+coord_flip()#Plot for 'd' Location
p1 #Plot for 'a' Location

enter image description here