Trouble with bar chart Binary data

I have these binary data:

spring summer fall winter
Lutajnus synagris 1 1 0 0
Lutjanus analis 1 1 0 0
Lutjanus apodus 1 0 0 0
Lutjanus cyanopterus 1 1 0 0
Lutjanus griseus 1 0 0 0
Lutjanus jocu 1 1 1 1
Ocyurus chysurus 0 1 0 0

and I need to make a similar bar chart in ggplot
lua-lut-bin

I don't know how to enter more than one variable on the x axis:
ggplot(dados, aes (x = spring, summer, fall, winter) + geom_bar() + theme_classic())
Error: Mapping should be created with aes() or aes_()`.
In addition: Warning message:
The plyr::rename operation has created duplicates for the following name(s): (``)

You need to convert your data to a long format for ggplot2, e.g. via tidyr::gather():

I'm not sure if this is what you are trying to do, but I think you can use this example as a starting point

library(tidyverse, quietly = TRUE)
binary_data <- data.frame(stringsAsFactors=FALSE,
                          Species = c("Lutajnus synagris", "Lutjanus analis", "Lutjanus apodus",
                                      "Lutjanus cyanopterus", "Lutjanus griseus", "Lutjanus jocu",
                                      "Ocyurus chysurus"),
                          spring = c(1, 1, 1, 1, 1, 1, 0),
                          summer = c(1, 1, 0, 1, 0, 1, 1),
                          fall = c(0, 0, 0, 0, 0, 1, 0),
                          winter = c(0, 0, 0, 0, 0, 1, 0)
)

binary_data %>% 
    gather('Season', 'Presence', -Species) %>%
    group_by(Season) %>% 
    summarise(n = sum(Presence)) %>% 
    ggplot(aes(x = Season, y = n)) +
    geom_col() +
    theme_classic()

Created on 2019-01-11 by the reprex package (v0.2.1)

3 Likes

Pretty much the same as @andresrcs, but as I had done it I'll post as well, it may help.

The fun bit for me was pulling the data from the post using datapasta which I saw in a blog post by Mara here: https://reprex.tidyverse.org/articles/articles/datapasta-reprex.html

library(magrittr)
library(ggplot2)
library(tidyr)

df <- data.frame(
    stringsAsFactors = FALSE,
    sp. = c(
        "Lutajnus synagris",
        "Lutjanus analis",
        "Lutjanus apodus",
        "Lutjanus cyanopterus",
        "Lutjanus griseus",
        "Lutjanus jocu",
        "Ocyurus chysurus"
    ),
    spring = c(1, 1, 1, 1, 1, 1, 0),
    summer = c(1, 1, 0, 1, 0, 1, 1),
    fall = c(0, 0, 0, 0, 0, 1, 0),
    winter = c(0, 0, 0, 0, 0, 1, 0)
)

df %>%
    gather(season, count, -sp.) %>%
    filter(count > 0) %>%
    ggplot(aes(season)) +
        geom_bar()

Created on 2019-01-11 by the reprex package (v0.2.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.