使用ggplot2在R上分组条形图

kna*_*aka 1 r ggplot2 geom-bar

如何ggplot2使用此数据在R上创建分组条形图?

Person Cats Dogs

Mr. A   3   1

Mr. B   4   2
Run Code Online (Sandbox Code Playgroud)

因此它显示了显示每人拥有的宠物数量,这个布局的宠物条形图

我有一个包含此数据的文本文件,并用于read.delim读取R上的文件.

我使用过这段代码,但它没有产生我正在寻找的条形图.

ggplot(data=pets, aes(x=Person, y=Cats, fill=Dogs)) + geom_bar(stat="identity", position=position_dodge())
Run Code Online (Sandbox Code Playgroud)

我是R的新手,任何帮助都将不胜感激.

提前致谢.

Sow*_*ian 9

要为分组条形图准备数据,请使用包的melt()功能reshape2

I.加载所需的包裹

    library(reshape2)
    library(ggplot2)
Run Code Online (Sandbox Code Playgroud)

II.创建数据框df

    df <- data.frame(Person = c("Mr.A","Mr.B"), Cats = c(3,4), Dogs = c(1,2))
    df
    #   Person Cats Dogs
    # 1   Mr.A    3    1
    # 2   Mr.B    4    2
Run Code Online (Sandbox Code Playgroud)

III.使用melt函数熔化数据

    data.m <- melt(df, id.vars='Person')
    data.m
    #   Person variable value
    # 1   Mr.A     Cats     3
    # 2   Mr.B     Cats     4
    # 3   Mr.A     Dogs     1
    3 4   Mr.B     Dogs     2
Run Code Online (Sandbox Code Playgroud)

IV.Grouped Bar情节Person

   ggplot(data.m, aes(Person, value)) + geom_bar(aes(fill = variable), 
   width = 0.4, position = position_dodge(width=0.5), stat="identity") +  
   theme(legend.position="top", legend.title = 
   element_blank(),axis.title.x=element_blank(), 
   axis.title.y=element_blank())
Run Code Online (Sandbox Code Playgroud)

顶部的图例,图例标题已删除,轴标题已删除,调整的条形宽度和条形之间的间距.

在此输入图像描述

  • 到目前为止我在网上找到的最好的解释 (3认同)