2

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



2 Answers 2

1
  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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.