簡體   English   中英

如何在 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 日創建

關鍵思想是:

  1. 使用列中的變量組織數據。
  2. Map 年齡組在 plot 中fill和/或color
  3. geom_col()中為分組條形圖設置position = "dodge"

您需要的是條形圖而不是直方圖。

  1. 使用pivot_longer將您的數據轉換為長格式
  2. 對條形圖使用geom_bar()
  3. geom_line()用於折線圖
  4. 庫(cowplot)到 plot 兩個圖並排
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.

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