首页 文章

如何在R中绘制多组数据? [关闭]

提问于
浏览
0

就像在情节found here中一样,我想在同一个条形图中显示多个数据集 .

我的数据基本上是各个国家的“男/女”高度 . 我想要沿着x轴的国家和两个条形图(一个蓝色的红色),每个国家的男性和女性高度 .

我已经挣扎了好几天了,但仍然没有弄明白 .

每个数据集当前都存储在自己的数据框中,第一列中的“countries”和第二列中的“height” . 所以我有一个male_heights和female_heights数据框 .

谢谢!

3 回答

  • 2

    这是一个虚拟数据的例子:

    # create some dummy data of two data.frames for male and female
    set.seed(45)
    dd.m <- data.frame(country = sample(letters[1:8]), height=sample(150:200, 8))
    dd.f <- data.frame(country = sample(letters[1:8]), height=sample(130:180, 8))
    
    # create an grp column for each of the above data.frames (M, F -> male, female)
    dd.m$grp <- "M"
    dd.f$grp <- "F"
    
    # merge data together
    dd <- rbind(dd.m, dd.f)
    
    # set levels for grp column - which one should be displayed first within the group
    # here, female followed by male
    dd$grp <- factor(dd$grp, levels=c("F", "M"), ordered=TRUE)
    
    # make sure country is a factor (reorder levels if you have to)
    dd$country <- factor(dd$country)
    
    # plot using ggplot
    require(ggplot2)    
    ggplot(data = dd, aes(x=country)) + 
          geom_bar(aes(weights=height, fill=grp), position="dodge") + 
          scale_fill_brewer(palette = "Set1")
    

    这给出了:
    enter image description here

  • 3

    首先,您应该根据国家/地区合并两个data.frame . 您可以使用例如ggplot2进行绘图 .

    以下是使用ggplot2的示例:

    # some data
    male_heights <- data.frame(country = LETTERS[1:20],
                               heights = runif(20, 10,20))
    female_heights <- data.frame(country = LETTERS[1:20],
                                heights = runif(20, 10,20))
    
    # merge both data.frame
    df_m <- merge(male_heights, female_heights, by = 'country', suffixes=c('_males', '_females'))
    
    # bring data to long format
    require(reshape2)
    dfm <- melt(df_m)
    
    # plot
    ggplot(dfm, aes(x = country, y = value, fill = variable)) +
      geom_bar(stat = 'identity', position = 'dodge')
    

    enter image description here

  • 4

    为了完整起见,这里有一些其他可用选项,一个在基础R中,另一个包含"lattice"包,通常与R一起安装 . 使用@ Arun的样本数据,这里是每个选项的基本示例 . (有很多方法可以自定义每个的外观 . )

    ## Base R -- Nothing fancy. 
    ## Requires a vector or matrix for your data
    barplot(xtabs(height ~ grp + country, dd), 
            beside = TRUE, col = c("red", "blue"))
    

    enter image description here

    ## lattice -- can work directly with your data.frame
    ## Several interesting options for groupings
    library(lattice)
    barchart(height ~ country, data = dd, groups = grp, 
             ylim = c(0, max(dd$height)+10), col = c("red", "blue"))
    

    enter image description here

相关问题