簡體   English   中英

如何在 R 中使用分類變量在堆積條形圖上放置數據標簽?

[英]How to place data labels on stacked bar chart with categorical variables in R?

如何使用以下數據集和代碼在堆積條形圖上放置數據標簽。 我收到Error: geom_text requires the following missing aesthetics: y and label當我使用+ geom_text(aes(X = Educational_status))時, Error: geom_text requires the following missing aesthetics: y and label

Age Sex Educational_status  State
44  Male    Illiterate       A
35  Male    PG               B
60  Male    UG               C
45  Female  Illiterate       D
45  Female  UG               A
34  Female  Illiterate       A

ggplot(data2, aes(x= Educational_status, fill=Sex))+
  geom_bar(position = "stack")+ 
   + facet_grid( ~ State)

也許這就是你正在尋找的。 要在條形圖上添加標簽,至少有兩種方法。 這兩種方法都需要計算y值以放置標簽並在label aes 上映射某些內容。

  1. 使用geom_bar你要告訴GGPLOT2計算count里面飛geom_text通過設置stat = "count" 如果您還想對標簽使用count ,則可以使用after_stat(count)

  2. 可能更簡單的方法是在將數據傳遞給 ggplot 並使用geom_col之前使用例如dplyr::count聚合數據。

library(ggplot2)

ggplot(data2, aes(x = Educational_status, fill = Sex)) +
  geom_bar() +
  geom_text(aes(label = after_stat(count)), stat = "count", position = "stack", vjust = 0) +
  facet_grid(. ~ State)

library(dplyr)

data3 <- data2 %>%
  count(Educational_status, Sex, State, name = "count")

ggplot(data3, aes(x = Educational_status, y = count, fill = Sex)) +
  geom_col() +
  geom_text(aes(label = count), position = "stack", vjust = 0) +
  facet_grid(. ~ State)

數據

data2 <- structure(list(Age = c(44L, 35L, 60L, 45L, 45L, 34L), Sex = c(
  "Male",
  "Male", "Male", "Female", "Female", "Female"
), Educational_status = c(
  "Illiterate",
  "PG", "UG", "Illiterate", "UG", "Illiterate"
), State = c(
  "A",
  "B", "C", "D", "A", "A"
)), class = "data.frame", row.names = c(
  NA,
  -6L
))

您不會說是否會有多個人具有相同的憑據,但如果只有一個人,那么這會為您提供標簽:

ggplot(data2, aes(x = Educational_status, y = 1, fill = Sex, label = Sex)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) +
  facet_grid( ~ State)

更改vjust以向上或向下移動標簽,如果您想要不同的標簽,請使用label = Sex

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM