首页 > 解决方案 > 吉特图上的数据签名

问题描述

下午好,亲爱的专业人士。我请您对一些我无法理解的问题提出答案。有以下一组数据:

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。我也想有如下图所示的数据标签。好吧,我还想要放置这些值的选项:

在此处输入图像描述

标签: rggplot2histogramdigital-signature

解决方案


尝试这个。使用构面并更改一些美学元素,您可以获得与您期望的相似的东西:

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

输出:

在此处输入图像描述


推荐阅读