首页 文章

绘制R中的分组条形图

提问于
浏览
9

我试图在R中绘制这些数据 -

column1  column2  column3
1-2       abc       10
1-2       def       15
1-2       ghi       20
2-3       abc       80
2-3       def       95
2-3       ghi       10
3-4       abc       30
3-4       def       55
3-4       ghi       80

x轴为column1(因此1-2,3-3和3-4将作为x轴存在),而在y轴上,应为每个column2元素绘制column3中的值 . 所以这将是一个“分组”的条形图 .

我无法使用R绘制这个分组的条形图 . 我使用的代码片段如下:

dataset <- fetch(rs,n=-1)
plot_var <- table(dataset$percentage, dataset$age)
barplot(plot_var, names.arg,
        main="Title of Graph",
        xlab="Column1", col=c("darkblue","red"),
        legend = rownames(plot_var), beside=TRUE)

如何显示此分组条形图?谢谢!

3 回答

  • 14

    您的问题似乎归结为错误的数据格式 . 您需要使用正确的行名称结构制作矩阵,以使用基本图形创建所需的绘图 . 这是你的解决方案:

    #your data...
    d <- data.frame(row.names=c("1-2","2-3","3-4"), abc = c(10,80, 30), 
                    def = c(15, 95, 55), ghi = c(20, 10, 80))
    #but you make a matrix out of it to create bar chart
    d <- do.call(rbind, d)
    #...and you are sorted
    barplot(d, beside = TRUE, ylim=c(0,100), legend.text = rownames(d), 
            args.legend = list(x = "topleft", bty="n"))
    

    enter image description here

    但是,我有时喜欢使用 lattice 来完成这项任务 . 这次你甚至不需要制作矩阵,你只需保留原始格式的 data.frame

    d <- data.frame(column1=rep(c("1-2","2-3","3-4"), each=3), 
                    column2=rep(c("abc", "def", "ghi"), 3), 
                    column3=c(10, 15, 20, 80, 95, 10, 30, 55, 80))
    require(lattice)
    barchart(column3 ~ column1, groups=column2, d, auto.key = list(columns = 3))
    

    enter image description here

  • 0

    我喜欢使用 ggplot2 来完成这项任务 .

    #Make the data reproducible:
    column1 <- c(rep("1-2", 3), rep("2-3", 3), rep("3-4", 3))
    column2 <- gl(3, 1, 9, labels=c("abc", "def", "ghi"))
    column3 <- c(10, 15, 20, 80, 95, 10, 30, 55, 80)
    
    d <- data.frame(column1=column1, column2=column2, column3=column3)
    
    require(ggplot2)
    ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(position=position_dodge())
    

    我发现这个直观的(在一段学习期之后)的原因是你在x和y轴上清楚地说明了你想要的东西,我们只是告诉ggplot(以及哪个变量定义'fill'颜色,以及哪种颜色)情节 - 这里, geom_bar - 使用 .

    enter image description here

  • 9

    我从Drew Steen的回答中找到了帮助,但上面的代码对我来说并不适合我 . 我添加了stat =“identity”并且它有效 .

    require(ggplot2)
    ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(stat="identity", position=position_dodge())
    

    谢谢你画了你的答案 .

相关问题