Tigran Minasyan
Tigran Minasyan

Reputation: 85

How to make R histogram centered?

I have made a histogram on some data, which has 3 features - race, gender, count. The histogram I plotted is like this:

enter image description here

But I want it to be centered for each gender, approximately like this: (random plot picture)

enter image description here

Here is my code

ggplot(bike_gender, aes(bikerace, Freq, fill = bikesex)) +
  geom_bar(stat = 'identity') + coord_flip() + theme_tufte() +
  labs(title = 'Bike crashes for people of different races and genders',
       x = 'Race', y = 'Number of accidents') +
  theme(plot.title = element_text(hjust = 0.5), axis.ticks = element_blank()) +
  scale_fill_brewer(name = 'Gender', palette = "Dark2")

Structure:

structure(list(bikerace = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 
1L, 2L, 3L, 4L, 5L, 6L), .Label = c("Asian", "Other", "Native American", 
"Hispanic", "Black", "White"), class = "factor"), bikesex = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Female", 
"Male"), class = "factor"), Freq = c(20L, 12L, 9L, 41L, 281L, 
708L, 52L, 62L, 82L, 349L, 2323L, 3377L)), class = "data.frame", row.names = c(NA, 
-12L))

Upvotes: 0

Views: 83

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You just need to conditionally flip the sign of Freq when bikesex is Female:

library(ggplot2)
library(ggthemes)
library(dplyr)


bike_gender %>% 
  mutate(Freq = ifelse(bikesex == "Female", -Freq, Freq)) %>%
  ggplot(aes(bikerace, Freq, fill = bikesex)) +
    geom_col() + 
    geom_hline(aes(yintercept = 0))+
    scale_y_continuous(breaks = 1000 * (0:6 - 3), 
                       labels = abs(1000 * (0:6 - 3)),
                       limits = c(-3500, 3500)) +
    coord_flip() + 
    theme_tufte() +
    labs(title = 'Bike crashes for people of different races and genders',
         x = 'Race', y = 'Number of accidents') +
    theme(plot.title = element_text(hjust = 0.5), axis.ticks = element_blank()) +
    scale_fill_brewer(name = 'Gender', palette = "Dark2")

enter image description here

Created on 2020-07-20 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions