首页 文章

如何在R中的图形上绘制多个分类变量?

提问于
浏览
1

我有大约10个分类变量 - pay1,pay2,...,pay10,每个变量的值为'Yes'或'No' . 我想在图表上绘制每个变量的计数 . 例如 - 图表上的bar1应该引用变量'pay1',反映在“是”和“否”之间划分的观察总数(“否”之上的“是”,反之亦然)此方案应与图表上的所有10个变量 . 如果我能够为每个条形显示“是”和“否”的百分比,那就更好了 . 有人能帮忙解决这个问题吗?

TIA .

2 回答

  • 0

    Edit 喜欢这个?

    set.seed(1) # make reproducible
    ### 3x variables, 5x observations
    df1 <- data.frame(x1=sample(c("yes","no"),5, replace=TRUE),
                      x2=sample(c("yes","no"),5, replace=TRUE),
                      x3=sample(c("yes","no"),5, replace=TRUE)
                      )
    library(reshape2)
    ### convert to 'long form'
    m1 <- melt(df1, measure.vars=c("x1","x2","x3"))
    ### now use facets to give one plot per variable
    library(ggplot2)
    qplot(variable, data=m1, fill=value) + facet_wrap( facets= ~variable, scale="free_x")
    

    赠送:

    enter image description here

    或者如果你想要'是/否'并排,这看起来对我来说更好:

    qplot(value, data=m1, fill=value) + facet_wrap( facets= ~variable, scale="free_x")
    
  • 1

    使用其他答案中生成的数据框,这个怎么样?我认为你必须非常具体地说明你希望你的x轴结构在这里得到一个有用的答案 .

    set.seed(1) # make reproducible
    ### 3x variables, 5x observations
    df1 <- data.frame(x1=sample(c("yes","no"),5, replace=TRUE),
                  x2=sample(c("yes","no"),5, replace=TRUE),
                  x3=sample(c("yes","no"),5, replace=TRUE)
                  )
    library(reshape2)
    m1 <- melt(df1, measure.vars=c("x1","x2","x3"))
    m1[,"varval"]<-paste(m1$variable, m1$value, sep="-")
    
    library(ggplot2)
    # All counts now have a common x-axis:
    varp<-ggplot(m1, aes(varv, fill=value))+geom_bar(stat="bin")
    varp
    

    samplefrequencyplot.jpeg

相关问题