R中有团体的条形图

时间:2016-10-28 05:35:20

标签: r plot bar-chart

我是R的新手,但我已经查看了很多教程,但我找不到解决方案。 我有这样的数据框:

FECRT <-
structure(list(Farm = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 
3L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 7L), .Label = c("5", 
"11", "15", "20", "24", "36", "47"), class = "factor"), Drug = 
structure(c(3L, 
2L, 1L, 3L, 2L, 2L, 4L, 1L, 3L, 4L, 2L, 4L, 1L, 3L, 4L, 1L, 3L, 
4L, 1L), .Label = c("Closantel", "Febendazole", "Ivermectin", 
"Moxidectin"), class = "factor"), Reduction = structure(c(10L, 
2L, 1L, 15L, 12L, 11L, 15L, 9L, 5L, 16L, 8L, 14L, 4L, 7L, 16L, 
3L, 6L, 16L, 13L), .Label = c("-64", "-6", "7", "17", "46", "49", 
"51", "53", "55", "64", "67", "82", "89", "90", "99", "100"), class =
"factor")), .Names = c("Farm", 
"Drug", "Reduction"), row.names = c(NA, -19L), class = "data.frame")

在农场我有7个农场,每个农场对一种疾病有一种或多种治疗方法,对于每种治疗,我有一种减少的结果(疾病结果的百分比)。我想要一个条形图显示轴Y减少(%),轴X显示农场ID。我输入了这个:

barplot(FECRT$"Reduction", name = Farmgroup, main="% EPG Reduction after treatment - FECRT Farms", xlab = "Farm ID", ylab = "EPG Percentual Reduction")

但是,我想按农场对X轴进行分组,因为每个农场可以有一到三种不同的处理方式。我尝试了函数表,然而,它创建了一个包含观察数量的表格,然后当我绘制它时,轴Y成为观察数量(0-3)。

我使用ggplot2aes使用dyplr尝试使用grouping_by,但也无效。

1 个答案:

答案 0 :(得分:0)

在ggplot中,将stat参数更改为“identity”非常重要,否则ggplot会因为默认值而占用计数。

    # Change Reduction from factor to numeric 
    FECRT$Reduction <- as.numeric(as.character(FECRT$Reduction))

    ggplot(FECRT, aes(x = Farm, y = Reduction, fill = Drug))+
      geom_bar(stat="identity", position = "dodge")

我将位置设置为闪避,因为叠加的条形图不能很好地处理负数。

干杯