這是我的資料和面積圖:
df<- data.frame(age=15:40,h1= 25:50,h2=35:60,h3=45:70)
data1<- df %>% gather(timeuse, minute, -age)
ggplot(data1, aes(x = age, y = minute, fill = timeuse))
geom_area()
scale_fill_brewer(palette = "Gray")
scale_x_continuous(breaks = seq(15, 90, by = 5))
scale_y_continuous(breaks = seq(0, 1500, by = 100))
theme_classic()
我想把圖例放在面積圖中,如下圖:

uj5u.com熱心網友回復:
一般來說,使用geom_textwith可以很容易地實作position = position_stack(vjust = 0.5)。根據您的真實資料,棘手的部分是選擇x要放置標簽的位置。在下面的代碼中,我使用dplyr::case_when為每個類別設定不同的位置timeuse。此外,根據您的真實資料,可能值得一看ggrepel::geom_text_repel。
library(ggplot2)
library(dplyr)
data1 <- data1 %>%
mutate(label = case_when(
timeuse == "h3" & age == 20 ~ timeuse,
timeuse == "h2" & age == 27 ~ timeuse,
timeuse == "h1" & age == 35 ~ timeuse,
TRUE ~ ""
))
p <- ggplot(data1, aes(x = age, y = minute, fill = timeuse))
geom_area()
scale_fill_brewer(palette = "Greys")
scale_x_continuous(breaks = seq(15, 90, by = 5))
scale_y_continuous(breaks = seq(0, 1500, by = 100))
theme_classic()
p
geom_text(aes(label = label), position = position_stack(vjust = 0.5))
guides(fill = "none")

uj5u.com熱心網友回復:
您可以使用注釋手動完成
annotate("text", x=50, y=2, label= "market work")
或者更自動化,像這樣(選擇你想要放置它們的行):
geom_text(data = df%>% group_by(timeuse) %>% sample_n(1),
aes(x = Age, y = minute,
label = rev(timeuse), color = rev(timeuse)),
position = position_stack(vjust = 0.5))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443254.html
