首页 文章

R上有两个不同变量的条形图

提问于
浏览
1

我想在同一个条形图上绘制以下数据 . 它是一个长度频率条形图,显示了人口中男性和女性的长度等级:

我是新手,我不知道如何把我的数据放在这里,但这是一个例子:

Lengthclass Both    Males   Females
60  7   5   2
70  10  5   5
80  11  6   5
90  4   2   2
100 3   3   0
110 3   0   3
120 1   1   0
130 0   0   0
140 1   0   1
150 2   0   2

如果我使用这个代码: {barplot()} 它不会在同一个图上给我所有三个变量 .

我需要一个看起来像这样的图,但是在R.
enter image description here

谢谢:)

2 回答

  • 3
    classes <- levels(cut(60:100, breaks = c(60,70,80,90,100),
                          right =FALSE))
    
    my.df <- data.frame(lengthclass = classes,
                         both = c(7,10,11,4),
                         male = c(5,5,6,2),
                         female = c(2,5,5,2))
    
    barplot(t(as.matrix(my.df[, 2:4])), 
            beside = TRUE,
            names.arg = my.df$lengthclass,
            legend.text = TRUE,
            ylim = c(0,12),
            ylab = "number of individuals",
            xlab = "Length class (cm)")
    
  • 1

    您的条形图被称为“分组条形图”(与“堆积条形图”相反) .

    将您的数据安排在 matrix 中,并在 barplot() 的通话中使用 beside=TRUE . 以下是使用内置数据集的示例:

    > VADeaths
          Rural Male Rural Female Urban Male Urban Female
    50-54       11.7          8.7       15.4          8.4
    55-59       18.1         11.7       24.3         13.6
    60-64       26.9         20.3       37.0         19.3
    65-69       41.0         30.9       54.6         35.1
    70-74       66.0         54.3       71.1         50.0
    > barplot(VADeaths,beside=TRUE)
    

    enter image description here

相关问题