[英]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 上映射某些內容。
使用geom_bar
你要告訴GGPLOT2計算count
里面飛geom_text
通過設置stat = "count"
。 如果您還想對標簽使用count
,則可以使用after_stat(count)
。
可能更簡單的方法是在將數據傳遞給 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
))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.