2

我一直在尝试创建条形图一段时间,但我需要帮助:

name    <- c('t1','t2')
reading <- c('yyyggrggryyy','grgrgrrryyyy')
df <- data.frame(name, reading)

读数值只能是“y”、“g”或“r”,字符串的长度始终为 12。我尝试将读数“转换”为每个名称的堆叠条形图,如下所示:

t1 堆叠条:

Color  Height
------ ------
yellow 3
green  2
red    1
green  2
red    1
yellow 3

谢谢

4

2 回答 2

7
> df <- data.frame(name=rep(name, each=12), 
                   reading=unlist(sapply(reading, strsplit, split="")))
> df
               name reading
yyyggrggryyy1    t1       y
yyyggrggryyy2    t1       y
yyyggrggryyy3    t1       y
yyyggrggryyy4    t1       g
snipped
grgrgrrryyyy4    t2       r
grgrgrrryyyy5    t2       g
grgrgrrryyyy6    t2       r
grgrgrrryyyy7    t2       r
grgrgrrryyyy8    t2       r
grgrgrrryyyy9    t2       y
grgrgrrryyyy10   t2       y
grgrgrrryyyy11   t2       y
grgrgrrryyyy12   t2       y

 qplot(reading,  data=df, geom="bar")+facet_grid(~name)

在此处输入图像描述

如果你想要一个堆叠的条形图,那么你需要传递一个与你想要堆叠的分组变量相同的 x 参数:

qplot(x=name,  data=df)+facet_grid(~name)+geom_bar(aes(fill = reading))

在此处输入图像描述

于 2013-08-06T21:38:46.360 回答
0
library(ggplot2)
m<-strsplit(as.character(df$reading),"") # split the strings 
data1<-as.data.frame(table(m[[1]])) # create dataframe for first element of reading
data2<-as.data.frame(table(m[[2]])) # create dataframe for second element of reading
t<-rep(c("t1","t2"),c(dim(data1)[1],dim(data2)[1])) 
t<-as.data.frame(t) # create dataframe of t which gives t1 and t2
mydata<-cbind(rbind(data1,data2),t)  #final data for plot
mydata$reading<-mydata$Var1
qplot(reading, data=mydata, geom="bar",weight=Freq)+facet_grid(~t)

在此处输入图像描述

于 2013-08-06T22:48:38.023 回答