简体   繁体   English

从 data.frame 创建条形图

[英]Create barplot from data.frame

In RI have a data.frame like the one on the top of the picture.在 RI 中有一个 data.frame,就像图片顶部的那个。

Is there a possibility to create a barplot like below?是否有可能创建如下所示的条形图?

data.frame:数据框:

      X1   X2   X3  
 --- ---- ---- ---- 
  A    2   3    4   
  B    4   2    1   
  C    1   NA   NA  

Barplot:条形图:

----------------------------
|                          |
|       #    #             |
|    #  #    #             |
| #  #  #    #  #          |
| #  #  #    #  #  #    #  |
----------------------------
  X1 X2 X3   X1 X2 X3   x1
     A           B       C

Using base graphics you can do this simply:使用基本图形,您可以简单地做到这一点:

mydf <- data.frame( X1=c(A=2, B=4, C=1), X2=c(3,2,NA), X3=c(4,1,NA) )
barplot(t(as.matrix(mydf)), beside=TRUE)

Using additional calls to axis can give the labeling more like in the question.使用对axis额外调用可以使标签更像问题中的标签。

Assuming, that you don't want ascii output, here is a solution using ggplot2 :假设您不想要 ascii 输出,这里是使用ggplot2的解决方案:

# load / generate your data
mydf <- data.frame( X1 = c(2,4,1), X2 = c(3,2,NA), x3 = c(4,1,NA), row.names=c("A","B","C") )
mydf$Category  <- row.names(mydf)

# bring your data to long format as needed by ggplot
library(reshape2)
mydf.molten <- melt(mydf, value.name="Count", variable.name="Variable", na.rm=TRUE)

# plot and facet by categories
library(ggplot2)
qplot( data=mydf.molten, x = Variable, y = Count, geom="bar", stat = "identity" ) + facet_wrap( "Category" )

在此处输入图片说明

For further details, I'd recommend to consult the ggplot2 manual , especially the chapter about geom_bar and facet_wrap .有关更多详细信息,我建议查阅ggplot2 手册,尤其是有关geom_barfacet_wrap的章节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM