尋求有關在 R 中創建堆疊圖的幫助。
示例資料:
Brand <- c('A', 'A', 'C', 'B', 'B', 'C', 'A, 'A', 'C', 'B', 'B', 'C', 'A'')
Month<- c( 'January', 'January', 'March', 'February', 'April', 'Spetember', 'May', 'July', 'June', 'November', 'December', 'October', 'August')
Value <- runif(13, 0.0, 30.0)
data <- data.frame(Brand , Month, Value)
這是我能夠做到的:
ggplot(data,
aes(x = Month,
y = Value,
group = Brand,
fill = Brand))
geom_area()
expand_limits( x = c(0,NA), y = c(0,NA))
scale_y_continuous(labels = scales::comma)
guides(fill = guide_legend(title = "Brand"))

這是期望的結果(用excel制作):

我們希望及時看到所有品牌的價值,如excel圖表所示。任何想法如何在 R 中使用 ggplot 實作類似的結果?
提前感謝任何想法
uj5u.com熱心網友回復:
我不確定這是否是問題所要求的。
geom_area的默認位置是position="stack",因此這些區域不應覆寫首先繪制的其他區域。因此,我認為問題在于資料不完整,即品牌和月份的某些組合沒有資料。下面的代碼使用tidyr::complete零填充這些值,然后繪制轉換后的資料。
注:發布的資料中,1月份品牌有重復"A"。我已將第二個品牌更改為"B".
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
library(ggplot2)
})
set.seed(2022)
Brand <- c('A', 'B', 'C', 'B', 'B', 'C', 'A', 'A', 'C', 'B', 'B', 'C', 'A')
Month<- c( 'January', 'January', 'March', 'February', 'April', 'September',
'May', 'July', 'June', 'November', 'December', 'October', 'August')
Value <- runif(13, 0.0, 30.0)
data <- data.frame(Brand , Month, Value)
data %>%
group_by(Brand) %>%
complete(Month = month.name,
fill = list(Value = 0)) %>%
mutate(Month = factor(Month, levels = month.name)) %>%
arrange(Brand, Month) %>%
ggplot(
aes(x = Month, y = Value, group = Brand, fill = Brand)
)
geom_area()
scale_y_continuous(labels = scales::comma)
scale_fill_manual(values = c(A = "#5f7530", B = "#772c2a", C = "#4bacc6"))
guides(fill = guide_legend(title = "Brand"))
theme_bw()
theme(
axis.text.x = element_text(angle = 45, vjust = 1, hjust=1),
legend.position = "bottom"
)

由
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/495179.html
上一篇:帶有資料標簽的多行(R)
下一篇:修復x軸ggplot上的特定日期
