Europa
Europa

Reputation: 1292

Plot variable with column chart with ggplot with data from read.csv2

I have the height of male and females in my data grouped by cm of 10. I want to plot them togheter side by side.

My graph looks somewhat what I want it to be, but the x-axis says factor(male). It should be height in cm.

Also I got three bars, but there should be two, one for male and one for female.

enter image description here


# Library
library(ggplot2)
library(tidyverse) # function "%>%"


# 1. Define data
data = read.csv2(text = "Height;Male;Female
160-170;5;2
170-180;5;5
180-190;6;5
190-200;2;2")

# 2. Print table
df <- as.data.frame(data)
df


# 3. Plot Variable with column chart 
ggplot(df, aes(factor(Male), 
                   fill = factor(Male))) + 
  geom_bar(position = position_dodge(preserve = "single")) + 
  theme_classic()



Upvotes: 2

Views: 285

Answers (2)

bird
bird

Reputation: 3326

One solution would be:

df %>%
        pivot_longer(cols = 2:3, names_to = "gender", values_to = "count") %>%
        ggplot(aes(x = Height, y = count, fill = gender)) +
        geom_bar(stat = "identity", position = "dodge") +
        theme_classic()

enter image description here

Upvotes: 0

TarJae
TarJae

Reputation: 79204

  1. pivot_longer to longformat
  2. Then use geom_bar with fill
library(tidyverse)
df1 <- df %>% pivot_longer(
  cols = c(Male, Female),
  names_to = "Gender", 
  values_to = "N"
)


# 3. Plot Variable with column chart 
ggplot(df1, aes(x=Height, y=N)) + 
  geom_bar(aes(fill = Gender), position = "dodge", stat="identity") +
  theme_classic()

enter image description here

Upvotes: 1

Related Questions