簡體   English   中英

面板數據和行 plot 用於 R 中的幾個變量

[英]Panel data and line plot for several variables in R

我有面板數據,其中“時間”變量表示年份,“unit_id”表示國家。 我想制作所有數字變量的行 plot (這些變量的值跨年份)。 一條線代表一個變量的所有國家/地區。

我試過了:

exampl%>%
  gather() %>%                             # Convert to key-value pairs
  ggplot(aes(time)) +                     # Plot the values
  facet_wrap(~ key, scales = "free") +   # In separate panels
  geom_line()

但它不起作用,我有一個錯誤:美學必須是有效的數據列。 有問題的美學:x = 時間。 您是否輸入錯誤數據列的名稱或忘記添加 after_stat()

那是我的數據:

dput(exampl)
structure(list(unit_id = c("AGO", "AGO", "AGO", "AGO", "AGO", 
"AGO", "BEN", "BEN", "BEN", "BEN", "BEN", "BEN", "BGD", "BGD", 
"BGD", "BGD", "BGD", "BGD", "CIV", "CIV", "CIV", "CIV", "CIV", 
"CIV"), time = c(2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2005L, 
2006L, 2007L, 2008L, 2009L, 2010L, 2005L, 2006L, 2007L, 2008L, 
2009L, 2010L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L), cab = c(28.2321949, 
29.25037956, 37.5, 31.28475761, 32.32411957, 33.39371109, 26.71179771, 
27.9, 28.71139336, 29.71598816, 30.73922729, 34.2, 44.23, 50.52510246, 
46.5, 52.65625763, 55.14787292, 55.26, 58.9, 53.74567795, 54.78623962, 
55.83730316, 56.8971138, 57.96392822), dit = c(13.89709218, 20.40781491, 
16.2123884, 8.125547549, -10.76938871, 8.957039766, -3.445136313, 
-3.090532362, -6.554877979, -5.520878675, -6.717259628, -5.567234574, 
-0.250193221, 1.66538338, 1.076211925, 1.01077433, 3.470143475, 
1.82904182, 0.232220267, 2.690679668, -0.683459128, 1.864047049, 
6.662914109, 1.866754256), fdi = c(-3.526655479, -0.072001021, 
-1.368761628, 1.896315051, 3.136662133, -3.851110464, -0.133873602, 
-0.175920935, 1.706123419, 0.49455672, -0.193899058, 0.561144791, 
1.17120896, 0.635657188, 0.817754424, 1.449748396, 0.879494542, 
1.068934861, 2.042272555, 1.969861557, 2.178644539, 1.925660984, 
1.631267003, 1.439124272), government = c(16.02903718, 15.34172241, 
15.5369347, 16.81461146, 19.89859034, 17.04234392, 8.991073644, 
9.666734707, 9.568485256, 10.23358845, 11.28862086, 11.21186949, 
5.180225165, 5.440078557, 5.359456215, 5.178276878, 5.093745166, 
5.075325836, 14.42744504, 13.59161479, 13.33857571, 12.66976339, 
12.63534697, 12.17758809)), class = "data.frame", row.names = c(NA, 
-24L))

您需要從gather調用中排除“時間”列,因為您需要每一行都有一個時間值。

您還需要為 geom_line 調用提供 x 和 y 美學。

嘗試這個:

exampl%>%
  tidyr::gather(key = "key", value = "value", -time, -unit_id) %>%
  ggplot(aes(x = time, y = value, color = unit_id)) +       
  facet_wrap(~ key, scales = "free") +   # In separate panels
  geom_line()

多面 ggplot 的示例圖片

您可能還想查看pivot_longer() 這是一個新版本的gather ,可能對用戶更加友好。

編輯(感謝 r2evans),這里是 pivot_longer。

exampl%>%
  tidyr::pivot_longer(
    -c(time, unit_id), 
    names_to = "key", 
    values_to = "value"
  ) %>%
  ggplot(aes(x = time, y = value, color = unit_id)) +                     
  facet_wrap(~ key, scales = "free") +   
  geom_line()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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