[英]How can one add a cumulative trend line based on weight to a histogram in R?
[英]how to draw group histogram graph and add trend line in R?
如上圖所示,我有類似的數據
year 0-19years_old 20-44years_old 45-64years_old above_65years old
2000 20000 34000 29000 16700
2005 19800 33000 28500 17000
我想在 r 中分別繪制每個年齡組的直方圖,以及 x 當前年份,y 當前計數。 如果為每個直方圖使用不同的顏色並在旁邊注明哪種顏色代表哪個年齡段,那就太好了。 還要繪制另一個線性圖,顯示每個年齡組在兩年內的變化情況,這里應該是 4 條不同顏色的線,但在一個圖中。
感謝大家的幫助!
像這樣的東西:
library(ggplot2)
library(tidyr)
dat <- tibble::tribble(
~year, ~`0-19`, ~`20-44`, ~`45-64`, ~`65+`,
2000, 20000, 34000, 29000, 16700,
2005, 19800, 33000, 28500, 17000
) |>
pivot_longer(
cols = -year,
names_to = "age_group",
values_to = "count"
)
dat
#> # A tibble: 8 x 3
#> year age_group count
#> <dbl> <chr> <dbl>
#> 1 2000 0-19 20000
#> 2 2000 20-44 34000
#> 3 2000 45-64 29000
#> 4 2000 65+ 16700
#> 5 2005 0-19 19800
#> 6 2005 20-44 33000
#> 7 2005 45-64 28500
#> 8 2005 65+ 17000
# Grouped bar chart
ggplot(dat) +
aes(x = year, y = count, fill = age_group) +
geom_col(position = "dodge")
# Line chart
ggplot(dat) +
aes(x = year, y = count, color = age_group) +
geom_line()
由代表 package (v2.0.0) 於 2021 年 5 月 30 日創建
關鍵思想是:
fill
和/或color
geom_col()
中為分組條形圖設置position = "dodge"
您需要的是條形圖而不是直方圖。
pivot_longer
將您的數據轉換為長格式geom_bar()
geom_line()
用於折線圖library(tidyverse)
library(cowplot)
df1 <- df %>%
pivot_longer(
cols = ends_with("old"),
names_to = "names",
values_to = "values"
)
a <- ggplot(df1, aes(x=factor(year), y=values, fill=names)) +
geom_bar(stat="identity", position = "dodge") +
geom_text(aes(label=values), vjust=1.6, color="black",
position = position_dodge(0.9), size=3.5)+
scale_fill_brewer(palette = "Set1")
b <- ggplot(df1, aes(x=factor(year), y=values, color=names, group=names)) +
geom_point() +
geom_line() +
scale_color_brewer(palette = "Set1")
plot_grid(a, b, labels = "AUTO")
數據:
df <- tribble(
~year, ~`0-19years_old`, ~`20-44years_old`, ~`45-64years_old`, ~`above_65years_old`,
2000, 20000, 34000, 29000, 16700,
2005, 19800, 33000, 28500, 17000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.