我一直在尝试创建一个条形图,但我需要帮助:
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
由于
答案 0 :(得分: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))
答案 1 :(得分: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)