簡體   English   中英

將堆積條形圖轉換為堆積面積圖

[英]Transform Stacked Bar chart into Stacked Area chart

我有一個帶有以下代碼的堆積條形圖:

ggplot(data_frame, aes(x = year, y = percent, fill = reorder(type, desc(percent)), label = round(percent, digits=2))) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

我正在嘗試使用以下代碼將其變成堆積面積圖:

ggplot(data_frame, aes(x=year, y=percent, fill=as.factor(type))) + 
    geom_area()

但是 plot 是空的或者不起作用。 有誰知道我在這里做錯了什么? 這是我第一次嘗試創建堆積面積圖。 先感謝您

我的dataframe如下:

structure(list(year = c(2012, 2013, 2013, 2014, 2014, 2015, 2015, 
2015, 2016, 2016, 2016, 2017, 2017, 2017, 2018, 2018, 2018, 2019, 
2019, 2019, 2020, 2020, 2020, 2021, 2021, 2021, 2022, 2022, 2022
), type = c("Blue", "Red", "Blue", "Red", "Blue", "Red", "Yellow", 
"Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", 
"Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", 
"Red", "Yellow", "Blue", "Red", "Yellow", "Blue"), percent = c(1, 
0.822493861837742, 0.177506138162258, 0.890831469712102, 0.109168530287897, 
0.813387070409725, 0.0497778071288365, 0.136835122461439, 0.864261238604485, 
0.036537301512893, 0.0992014598826223, 0.869551858365865, 0.0555953345546625, 
0.0748528070794728, 0.830539033602976, 0.075436440035225, 0.0940245263617988, 
0.775315022945149, 0.0633554986887996, 0.161329478366051, 0.601100639265675, 
0.254061406486953, 0.144837954247372, 0.630357987198663, 0.203272744842328, 
0.166369267959009, 0.660638396593096, 0.174442088167586, 0.164919515239318
)), row.names = c(NA, -29L), class = "data.frame")

有時geom_area會遇到麻煩,因為類別在每個步驟中的表示不一致。 (我假設在幕后,它不知道新出現的類別是否應該立即開始,或者它是否應該在前面的步驟中從零開始增加。我通常(總是?)想要后一種行為,但它不是默認值。)

一種快速解決方法是使用tidyr::complete來填充所有未表示的類型。

df |>
  tidyr::complete(year, type, fill = list(percent = 0)) |>
  ggplot(aes(x=year, y=percent, fill=as.factor(type))) +
  geom_area()

在此處輸入圖像描述

沒有complete :(我正在使用 ggplot2 v3.4.0)

在此處輸入圖像描述

暫無
暫無

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

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