r - 吉特图上的数据签名
问题描述
下午好,亲爱的专业人士。我请您对一些我无法理解的问题提出答案。有以下一组数据:
df<-data.frame(num = c(1:20),
gender=unlist(strsplit("MFFMMMFMFMMMMMFFFMFM","")),
age= sample(1:100, 20, replace=T),
entrance=sample(1:4, 20, replace=T))
数据被排序和分组。
df <- group_by(df, df$entrance, df$gender)
实际上,根据数据,构建了一个图
ggplot(df, aes(x= df$entrance)) +
geom_bar(aes(fill=df$gender), position = "dodge")+
scale_fill_discrete(name = "Title", labels = c("F", "M"))+
xlab("Distribution of residents by entrances, taking into account gender")+
ylab("Number of residents")
实际上,结果如下:
我不喜欢什么?我想如果类别中没有数据,则不绘制列,而是指示0。我也想有如下图所示的数据标签。好吧,我还想要放置这些值的选项:
- 底部(如图所示);
- 在条带的中心;
- 在条带的顶部。
解决方案
尝试这个。使用构面并更改一些美学元素,您可以获得与您期望的相似的东西:
library(ggplot2)
library(dplyr)
#Plot
df %>% group_by(entrance,gender) %>%
summarise(N=n()) %>%
mutate(gender=factor(gender,levels = c('F','M'))) %>%
complete(gender,fill = list(M=0,F=0)) %>%
replace(is.na(.),0) %>%
ggplot(aes(x= factor(gender),y=N,fill=gender)) +
geom_bar(stat='identity', position = position_dodge2(0.9))+
geom_text(aes(label=N,y=0),vjust=-0.5,position = position_dodge2(0.9))+
scale_fill_discrete(name = "Title", labels = c("F", "M"))+
facet_wrap(.~entrance,nrow = 1,strip.position = 'bottom')+
xlab("Distribution of residents by entrances, taking into account gender")+
ylab("Number of residents")+
theme(strip.placement = 'outside',
strip.background = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
输出:
推荐阅读
- c - 使用 C 生成位图图像:第一行像素损坏
- python - 如何用 pip 替换现有环境来重现 Python 环境?
- android - 在第二个列表中查找丢失对象然后使用 Kotlin 添加它的更好方法
- javascript - 过滤从 Promise 返回的数组
- keras - 如何使用 scikit learn 的 MLP 分类器可视化模型训练历史?
- postgresql - 无法重新连接到 postgresql 数据库
- python - 不确定 tensorflow 是否在 GPU 或 CPU 自定义 keras 训练循环上运行,或者它是否与训练循环代码有关
- pandas - 如何根据与另一列的所有先前值相关的函数在熊猫中创建新列
- python - Webscraper 不会从第 2 页循环到第 5 页
- r - 如何解决 predict() 中的错误:进行二进制分类时 R 中的下标越界?