Camila Queiroz Camila Queiroz - 1 month ago 17
R Question

Barplots with groups in R

I'm new at R but I have looked in many tutorials and I can't find a solution.
I have a dataframe like this:

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")


Where in Farm I have 7 farms, each farm has one or more treatments for one disease and for each treatment I have one result for Reduction (% in disease outcome). I want a barplot showing the axis Y the Reduction(%), and the axis X the Farm ID. I got this by typing:

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


However, I want to group the axis X by farm, since each farm can have one or three different treatments. I tried the function table, however, it creates a table with the number of observations and then when I plot it, the axis Y becomes the number of observations (0-3).

I tried with
ggplot2
using
aes
and
dyplr
using
grouping_by
but also doesn't work.

Answer

In ggplot it is important to change the stat argument to "identity" otherwise ggplot takes the count because of its default.

    # 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")

I set position to dodge because stacked bar charts don't handle negative numbers well.

Cheers