我有資料框,它代表 2 年內不同型號的銷售額。“變化”列代表從 2020 年到 2021 年模型的絕對變化,而“chng.percent”以百分比衡量這種變化。
df <- data.frame (model = c("A", "A", "B","B"),
year = c(2020,2021,2020,2021),
sale =c(105,190,110,180),
chang = c(85,NA,70,NA),
chng.percent = c(80.9,NA, 63.6,NA))
現在我正在努力在 R 中構建斜率圖:(
我想構建斜率地塊 根據模型分類變數添加絕對和百分比的變化 線條顏色
預期輸出:

uj5u.com熱心網友回復:
那這個呢:
library(tidyverse)
df <- data.frame (model = c("A", "A", "B","B"),
year = c(2020,2021,2020,2021),
sale =c(105,190,110,180),
chang = c(85,NA,70,NA),
chng.percent = c(80.9,NA, 63.6,NA))
labs <- df %>%
group_by(model) %>%
slice_head(n=1)
ggplot(df, aes(x=year, y=sale, colour = model))
geom_line(show.legend = FALSE)
geom_point()
geom_text(data = subset(df, year==2020), aes(x=year, y=sale, label=sale), hjust=1, nudge_x = -.05, show.legend = FALSE, inherit.aes = FALSE)
geom_text(data = subset(df, year==2021), aes(x=year, y=sale, label=sale), hjust=0, nudge_x = .05, show.legend = FALSE, inherit.aes = FALSE)
geom_text(aes(x=2020.75, y=140, label = sprintf(" %.1f, %.1f%%", labs$chang[2], labs$chng.percent[2]), colour=labs$model[2]), show.legend = FALSE)
geom_text(aes(x=2020.75, y=175, label = sprintf(" %.1f, %.1f%%", labs$chang[1], labs$chng.percent[1]), colour=labs$model[1]), hjust=1, show.legend = FALSE)
geom_vline(xintercept = unique(df$year))
scale_x_continuous(breaks = c(2020,2021), labels=c(2020, 2021))
coord_cartesian(xlim=c(2019.75, 2021.25))
theme_minimal()
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid = element_blank())
labs(colour ="", y="", x="")

由reprex 包于 2022-05-12 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474403.html
