Marco Mariani
Marco Mariani

Reputation: 107

How to arrange Xticks in ggplot for categorical variables

I am having trouble visualizing the "sex" variable (Female=0, Male=1) from the "heart_data" dataframe. Here's my code:

ggplot(heart_data, aes(x = sex)) + geom_bar()

And this is what I obtain:

enter image description here

What should I do in order to display just 0 and 1 or, preferably, Female and Male on the Xaxis?

Upvotes: 0

Views: 100

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

To display 0/1 on x-axis convert sex to factor.

library(dplyr)
library(ggplot2)

hear_data %>%
  mutate(sex = factor(sex)) %>%
  ggplot(aes(x = sex)) + geom_bar()

To display Female/Male recode 0/1 value.

hear_data %>%
  mutate(sex = recode(sex, `1` = 'Male', `0` = 'Female')) %>%
  ggplot(aes(x = sex)) + geom_bar()

Upvotes: 1

Related Questions