如何在 aggregate(...,hist) 命令中输入标题?
How to input titles in a aggregate(...,hist) command?
我正在尝试自动创建具有适当标题的直方图。
a <- c('aaa','bbb','ccc','aaa','bbb','ccc','aaa',
'bbb','ccc','aaa','bbb','ccc','aaa','bbb','ccc');
b <- rnorm(15,0,1);
c <- data.frame(a,b);
regions<-sort(unique(a));
有没有办法在我的 aggregate(
命令中输入 regions
object 来执行我想要的操作?
我想象的另一种选择是使用循环和使用 split()
的数据帧列表,但我想避免它。
这样的事情怎么样?
a <- c('aaa','bbb','ccc','aaa','bbb','ccc','aaa',
'bbb','ccc','aaa','bbb','ccc','aaa','bbb','ccc');
b <- rnorm(15,0,1);
c <- aggregate(b,by=list(a),FUN=sum)
barplot(c$x, names.arg=c$Group.1,space = 0)
如果您尝试创建三个直方图,每个区域一个,并适当地命名,您可以使用 sapply
来避免显式编写循环。
# rename your data.frame c as df
colnames(df) <- c('region', 'val')
# filter your df by region, and create a title histogram
sapply(regions, function(x) hist(df[df['region'] == x, 2], main=x)
结果仍然需要一些爱,但这应该让您开始使用三个单独命名的直方图。
这里有两个ggplot解决方案
# create more interesting example
set.seed(1) # for reproducibility
a <- rep(c('aaa','bbb','ccc'), each=100)
b <- rnorm(length(a),mean=rep(1:3, each=100))
c <- data.frame(a,b)
library(ggplot2)
ggplot(c, aes(x=b, fill=a, color=a)) +
geom_histogram(binwidth=0.5, position="identity", alpha=.5)
ggplot(c, aes(x=b, fill=a)) +
geom_histogram(binwidth=0.5, position="identity", color="grey70")+
facet_grid(a~.)
我正在尝试自动创建具有适当标题的直方图。
a <- c('aaa','bbb','ccc','aaa','bbb','ccc','aaa',
'bbb','ccc','aaa','bbb','ccc','aaa','bbb','ccc');
b <- rnorm(15,0,1);
c <- data.frame(a,b);
regions<-sort(unique(a));
有没有办法在我的 aggregate(
命令中输入 regions
object 来执行我想要的操作?
我想象的另一种选择是使用循环和使用 split()
的数据帧列表,但我想避免它。
这样的事情怎么样?
a <- c('aaa','bbb','ccc','aaa','bbb','ccc','aaa',
'bbb','ccc','aaa','bbb','ccc','aaa','bbb','ccc');
b <- rnorm(15,0,1);
c <- aggregate(b,by=list(a),FUN=sum)
barplot(c$x, names.arg=c$Group.1,space = 0)
如果您尝试创建三个直方图,每个区域一个,并适当地命名,您可以使用 sapply
来避免显式编写循环。
# rename your data.frame c as df
colnames(df) <- c('region', 'val')
# filter your df by region, and create a title histogram
sapply(regions, function(x) hist(df[df['region'] == x, 2], main=x)
结果仍然需要一些爱,但这应该让您开始使用三个单独命名的直方图。
这里有两个ggplot解决方案
# create more interesting example
set.seed(1) # for reproducibility
a <- rep(c('aaa','bbb','ccc'), each=100)
b <- rnorm(length(a),mean=rep(1:3, each=100))
c <- data.frame(a,b)
library(ggplot2)
ggplot(c, aes(x=b, fill=a, color=a)) +
geom_histogram(binwidth=0.5, position="identity", alpha=.5)
ggplot(c, aes(x=b, fill=a)) +
geom_histogram(binwidth=0.5, position="identity", color="grey70")+
facet_grid(a~.)