Как установить тег с количеством наблюдений в верхней части столбца с накоплением - PullRequest
0 голосов
/ 07 июня 2019

Я хочу установить количество наблюдений в верхней части каждого бара. Это пример данных

structure(list(Treatment = structure(c(3L, 3L, 3L, 3L, 3L, 4L, 
4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L), .Label = c("", "{\"ImportId\":\"Treatment\"}", 
"Altruism", "Altruism - White", "Piece Rate - 0 cents", "Piece Rate - 3 cents", 
"Piece Rate - 6 cents", "Piece Rate - 9 cents", "Reciprocity", 
"Reciprocity - Black", "Reciprocity - White", "Treatment"), class = "factor"), 
    Gender = structure(c(5L, 3L, 5L, 5L, 5L, 3L, 3L, 7L, 3L, 
    3L, 5L, 5L, 3L, 3L, 5L), .Label = c("", "{\"ImportId\":\"QID2\"}", 
    "Female", "Gender you most closely identify with: - Selected Choice", 
    "Male", "Other", "Prefer not to answer"), class = "factor")), row.names = c(NA, 
15L), class = "data.frame")

Мой подход заключался в использовании следующего кода

totals <- Data1 %>%
  group_by(Gender) %>%
  summarize(total = n)

Data1 %>% 
  count(Treatment, Gender) %>% 
  ggplot(aes(Treatment, n))+ 
  geom_col(aes(fill = Gender), position = "fill")+
  ggtitle("Gender")+
  ylab("Fraction")+
  theme(axis.text.x = element_text(angle = 90, vjust=0.3, hjust=1))+
  scale_fill_manual("Gender", 
                    values = c("Female" = "pink", "Male" = "light blue",
                               "Other"="coral", "Prefer not to answer"="violet"))+
  geom_text(aes(label=n, group=Gender),size=3, 
            position = position_fill(vjust=0.5),data<-totals)

Я хочу, чтобы общее количество наблюдений отображалось в верхней части каждого столбца. Мой график пока выглядит так

enter image description here

Теперь я хочу знать, как отображать общее количество наблюдений для каждого столбца.

1 Ответ

1 голос
/ 07 июня 2019

Я не смог заставить ваши образцы данных работать, вот пример добавления итогов к каждому столбцу.

Вам нужно будет создать еще один набор данных, который будет отображать итоги по каждой группе (для вашего примера это будет Treatment). Затем добавьте geom_text для ваших итогов.

library(dplyr)
library(ggplot2)
library(scales)

# Sample Data
Data1 <- data.frame(
  Gender = factor(c("Female","Female","Male","Male")),
  Treatment = factor(c("a","b","a","b"), levels=c("a","b")),
  value = c(10, 12, 13, 11)
)

# Totals for each bar
totals <- Data1 %>%
  group_by(Treatment) %>%
  summarize(value = sum(value))

# Bar chart
ggplot(data=Data1, aes(x=Treatment, y=value)) +
  geom_bar(stat="identity", aes(fill=Gender)) + 

  # comment this out if you don't want to show labels for each stacked bar
  geom_text(aes(label = value),position = position_stack(vjust = 0.5))+

  # Add totals for each bar   
  geom_text(data = totals, aes(x = Treatment, y = value, label = value))

РЕДАКТИРОВАТЬ (с данными образца)

library(dplyr)
library(ggplot2)
library(scales)

totals <- Data1 %>% 
  count(Treatment)

Data1 %>% 
  count(Treatment, Gender) %>% 
  ggplot(aes(x = Treatment, y = n)) + geom_bar(stat = "identity", aes(fill = Gender)) +
  ggtitle("Gender") + ylab("Fraction") + 
  theme(axis.text.x = element_text(angle = 90, vjust=0.3, hjust=1)) +
  scale_fill_manual("Gender", 
                    values = c("Female" = "pink", "Male" = "light blue",
                               "Other"="coral", "Prefer not to answer"="violet")) +

  # Add totals for each bar   
  geom_text(data = totals, aes(label = n))

enter image description here

...