首页 > 解决方案 > 如何使R直方图居中?

问题描述

我对一些数据做了一个直方图,它有 3 个特征——种族、性别、计数。我绘制的直方图是这样的:

在此处输入图像描述

但我希望它以每个性别为中心,大致如下:(随机情节图片)

在此处输入图像描述

这是我的代码

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

标签: rggplot2histogram

解决方案


您只需要有条件地翻转Freqwhen bikesexis的符号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")

在此处输入图像描述

reprex 包(v0.3.0)于 2020-07-20 创建


推荐阅读