r - 如何使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))
解决方案
您只需要有条件地翻转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")
由reprex 包(v0.3.0)于 2020-07-20 创建
推荐阅读
- c++ - 如何将包含其他对象向量的对象写入文件?
- java - 我的比较器的比较方法不起作用
- javascript - React select - 更改所选值的显示方式
- linux - 文件中带有特殊字符的 grep 字符串
- machine-learning - 如何从 k 折交叉验证中的每个折中学习?
- gnuplot - 如何仅使用线点和使用gnuplot的多个图绘制由ID列指定的点?
- reactjs - 如何使用 react-scripts 安装 NPM 插件
- docker - 我们可以控制 .dockerignore 文件中内容的区分大小写吗?
- c# - 无法将 C# 字符串从用户态传递到内核模式 C 并使用它来查找特定的 LDR_DATA_TABLE_ENTRY
- python - Flask 根据激活的按钮获得相同的页面结果