[英]How to implement stacked bar graph with a line chart in R
我有一個包含 y 變量為Year和 x 變量為(A, B, C(%))的數據集。 我在這里附上了數據集。
dput(result)
structure(list(Year = 2008:2021, A = c(4L, 22L, 31L, 48L, 54L,
61L, 49L, 56L, 59L, 85L, 72L, 58L, 92L, 89L), B = c(1L, 2L, 6L,
7L, 14L, 21L, 15L, 27L, 27L, 46L, 41L, 26L, 51L, 62L), C... = c(25,
9.09, 19.35, 14.58, 25.93, 34.43, 30.61, 48.21, 45.76, 54.12,
56.94, 44.83, 55.43, 69.66)), class = "data.frame", row.names = c(NA,
-14L))
變量 A 和 B 將繪制為堆積條形圖,C 將繪制為同一圖中的折線圖。 我已經使用 excel 生成了如下圖:
如何在 R 中創建相同的圖?
您首先需要重新塑造更長的形狀,例如使用 tidyr 中的tidyr
pivot_longer()
,然后您可以使用ggplot2
在兩個單獨的圖層中繪制條形圖和線條。 geom_bar(aes())
中的fill =
參數可讓您根據分類變量對每個柱進行分層 - name
由pivot_longer()
自動創建。
library(ggplot2)
library(tidyr)
dat |>
pivot_longer(A:B) |>
ggplot(aes(x = Year)) +
geom_bar(stat = "identity", aes(y = value, fill = name)) +
geom_line(aes(y = `C(%)`), size = 2)
由reprex 包(v2.0.1) 創建於 2022-06-09
您要求疊加條,在這種情況下無需旋轉,您可以添加單獨的圖層。 但是我認為這可能會混淆或誤導許多人 - 通常在堆疊的情節中,條形圖是堆疊的,而不是重疊的,因此請謹慎使用!
library(ggplot2)
library(tidyr)
dat |>
ggplot(aes(x = Year)) +
geom_bar(stat = "identity", aes(y = A), fill = "lightgreen") +
geom_bar(stat = "identity", aes(y = B), fill = "red", alpha = 0.5) +
geom_line(aes(y = `C(%)`), size = 2) +
labs(y = "", caption = "NB: bars are overlaid, not stacked!")
由reprex 包(v2.0.1) 創建於 2022-06-09
我提出這個:
library(data.table)
library(ggplot2)
library(ggthemes)
dt <- fread("dataset.csv")
dt.long <- melt(dt, id.vars = c("Year"))
dt.AB <- dt.long[variable %in% c("A", "B"), ]
dt.C <- copy(dt.long[variable == "C(%)", .(Year, variable, value = value * 3/2)])
ggplot(dt.AB, aes(x = Year, y = value, fill = variable), ) +
geom_bar(stat = "identity") +
geom_line(data=dt.C, colour='red', aes(x = Year, y = value)) +
scale_x_continuous(breaks = pretty(dt.AB$Year,
n = length(unique(dt.AB$Year)))) +
scale_y_continuous(
name = "A&B",
breaks = seq (0, 150, 10),
sec.axis = sec_axis(~.*2/3, name="C(%)", breaks = seq (0, 100, 10))
) + theme_hc() +
scale_fill_manual(values=c("grey70", "grey50", "grey30")) +
theme(
axis.line.y = element_line(colour = 'black', size=0.5,
linetype='solid'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.