我已经提供的数据已经包含了类别的总数。我正在尝试为每个com和年龄制作房屋数量的直方图,其中Houses是该类别的总数。
Com<-c( "Newport", "Newport", "Newport", "Newport", "Newport", "Newport", "Topeka", "Topeka", "Topeka", "Topeka", "Topeka", "Topeka", "Missoula", "Missoula", "Missoula", "Missoula", "Missoula", "Missoula" )
Age<-c( "1970s", "1960s", "1950s", "1940s", "1940_earlier", "1990s", "1970s", "1960s", "1950s", "1940s", "1940_earlier", "1990s", "1970s", "1960s", "1950s", "1940s", "1940_earlier", "1990s" )
Houses<-c( 11, 6, 3, 0, 0, 21, 44, 0, 3, 3, 25, 20, 0, 51, 236, 192, 312, 299 )
df=data.frame(Com,Age,Houses)
所以df是数据
histogram( ~ Age | Com, data=df)
我也试过
install.packages("ggplot2")
library(ggplot2)
g <- ggplot(df$counts, aes(df$Age))
g + geom_bar()
另外
barplot(prop.table(table(df$Age)))
最后
p <- ggplot(data = df, aes(x=Age))
p <- p + geom_histogram(aes(weights=Houses, fill=Com))
p <- p + scale_fill_brewer(palette="Set3")
p <- p + facet_wrap( ~ Com, ncol=1)
p
这是我的R版本信息:
R.Version()
$platform
[1] "x86_64-w64-mingw32"
$arch
[1] "x86_64"
$os
[1] "mingw32"
$system
[1] "x86_64, mingw32"
$status
[1] ""
$major
[1] "3"
$minor
[1] "3.0"
$year
[1] "2016"
$month
[1] "05"
$day
[1] "03"
$`svn rev`
[1] "70573"
$language
[1] "R"
$version.string
[1] "R version 3.3.0 (2016-05-03)"
$nickname
[1] "Supposedly Educational"
答案 0 :(得分:1)
在geom_bar()
中使用已经计算过的总计ggplot2
时(而不是需要对案例进行计数或求和),您需要指定stat="identity"
。 <怎么样
g0 <- ggplot(df,aes(Age,Houses))+
geom_bar(stat="identity")+
facet_wrap(~Com)
print(g0)
?或
ggplot(df,aes(Age,Houses))+
geom_bar(stat="identity")+
coord_flip()+
facet_wrap(~Com,ncol=1)
答案 1 :(得分:1)
格子函数是条形图:
library(lattice)
barchart( Houses ~ Age ,group=Com, data=df)
基本条形图解决方案要求数据位于矩阵,表格或xtabs对象中。通过defatul你得到一个堆栈条形图,但是如果你和上面的格子代码一样,你可以添加旁边的参数:
barplot(xtabs(Houses~Com+Age, data=df), beside=TRUE)