R:在多列数据帧上的Facet ggplot条形图

时间:2014-05-23 13:24:56

标签: r ggplot2

我有以下数据框:

df = data.frame(ID=c(1,2,3), A=c(0,1,1), B=c(0,2,1), C=c(0,2,2))
df[df=="0"]<-NA;
df[df=="1"]<-"Less";
df[df=="2"]<-"Average";
df[df=="3"]<-"More";
# reset the id row again --- i know its lame, is there a better way?
df$ID = c(1:3);
# turn to factors
df$A = factor(df$A, levels = c("NA", "Less", "Average", "More"));
df$B = factor(df$B, levels = c("NA", "Less", "Average", "More"));
df$C = factor(df$C, levels = c("NA", "Less", "Average", "More"));

我确信这不是一个完美的实现,我愿意接受如何做得更好的建议:)

如何使用ggplot创建A,B和C的刻面条形图?此条形图将显示3个条形图(每个数据框的一列),每个条形图中有4个条形图,NA,Less,Average等等。我不确定与???的部分?但希望下面的代码片有助于......

ggplot(df$???, aes(value, fill=???)) + 
geom_bar(aes(y = (..count..)/totalNumber)) + facet_wrap(~???) + 
theme(
  axis.text.x = element_text(angle = 45, hjust = 1, face=2), 
  axis.text=element_text(size=12), axis.title=element_text(size=14,face="bold"),   
  panel.background = element_rect(fill = "white")
) +   
scale_fill_manual(values=c("blue4","steelblue2", "blue4","steelblue2",   
  "blue4","steelblue2")) + opts(legend.position = "none") +   
scale_y_continuous(breaks=seq(0, 1, 0.1), labels = percent_format()) + 
xlab("") + ylab("") + 
coord_flip();

提前致谢!

最佳, 拉尔夫

1 个答案:

答案 0 :(得分:2)

您需要melt您的数据,即将其格式化为长格式:

library("reshape2")
df.molten <- melt(df, id.vars="ID")
head(df.molten)
  ID variable   value
1  1        A    <NA>
2  2        A    Less
3  3        A    Less
4  1        B    <NA>
5  2        B Average
6  3        B    Less

ggplot( df.molten , aes( x = value )  )+ 
  geom_bar() +
  facet_wrap( "variable" )

enter image description here

编辑:

关于未使用的因子级别More,您必须在再次融化后分配级别:

df.molten$value <- factor( df.molten$value, levels = c("NA", "Less", "Average", "More") )

即使您使用melt的参数value.factor = TRUE,在熔化时也会丢弃未使用的因子级别。此外,您必须添加

+ scale_x_discrete( drop = FALSE )

到你的情节,如ggplot2 keep unused levels barplot

中所述

enter image description here