[R語言圖表]用ggplot畫折線圖 line chart

5

Last Updated on 2023-10-31

Home » R語言教學 » 資料視覺化 » [R語言圖表]用ggplot畫折線圖 line chart

你想畫折線圖(line chart)嗎?用 ggplot2 帶你畫!


想用R語言畫折線圖(line chart ),但是不知道怎麼使用相關函數嗎?什麼時候該用折線圖?想一次呈現好幾條折線怎麼辦?

我會在這篇文章介紹如何活用R語言的套件ggplot2,配上實際程式碼,帶你畫山脊圖。

折線圖 line chart 是什麼?

折線圖(line chart)指的是用線條將資料點連結在一起的圖表,可以用來呈現變數的歷史變化。

單張圖表中,有時候會同時呈現好幾條線,用來較不同變數的差異,舉例來說,我們在這篇文章就是想呈現台灣人對海峽兩岸呈不同立場的變化趨勢,因此橫軸會呈現時間,縱軸則是認同變化,分為三種類別:暫時或永遠維持變化、偏向獨立或希望盡快獨立、偏向統一或希望盡快統一。

r line chart,以折線圖呈現台灣人對兩岸未來走向時間變化的例子
以折線圖呈現台灣人對兩岸未來走向時間變化的例子

在繪製折線圖的時候,我們想檢視的變數會映射(mapping,指的是想呈現的變量對應到圖表中的表示方法)到y軸,時間則映射到x軸。

在 R 語言中,我們可以快速地利用 ggplot2 套件輕鬆簡單的畫出折線圖。底下會一步一步帶大家實作。

實作篇

資料長相

我們先來匯入資料。從底下的表格可以看到,這份資料是從1994年至今的「民眾對兩岸未來走向立場」的時間變化。

library(tidyverse)
df_crossstraight <- read_csv("data/df_crossstraight.csv")
df_crossstraight
#> # A tibble: 29 × 8
#>     year 維持現狀再決定 無反應 偏向統一 永遠維持現狀 偏向獨立 儘快統一 儘快獨立
#>    <dbl>          <dbl>  <dbl>    <dbl>        <dbl>    <dbl>    <dbl>    <dbl>
#>  1  1994           38.5   20.5     15.6          9.8      8        4.4      3.1
#>  2  1995           24.8   26.3     19.4         15.6      8.1      2.3      3.5
#>  3  1996           30.5   18.6     19.5         15.3      9.5      2.5      4.1
#>  4  1997           30.5   15.4     17.3         16.3     11.5      3.2      5.7
#>  5  1998           30.3   18.7     15.9         15.9     11.5      2.1      5.7
#>  6  1999           30.9   14.5     15.2         18.8     13.6      2.2      4.7
#>  7  2000           29.5   17.4     17.3         19.2     11.6      2        3.1
#>  8  2001           35.9   13.3     17.5         16.4     10.5      2.8      3.7
#>  9  2002           36.2   12.4     15.7         15       13.8      2.5      4.3
#> 10  2003           35     12.5     11.9         18       14.5      1.8      6.2
#> # … with 19 more rows

由於這是一張寬表格(wide table),我們需要利用 pivot_longer()
將其轉換為長表格(long table),後續才方便繪圖。

df_crossstraight_long <- df_crossstraight %>% 
  pivot_longer(cols = -1, names_to = "type", values_to = "n") %>%
  filter(!is.na(n)) %>%
  mutate(n = n/100)

df_crossstraight_long
#> # A tibble: 203 × 3
#>     year type               n
#>    <dbl> <chr>          <dbl>
#>  1  1994 維持現狀再決定 0.385
#>  2  1994 無反應         0.205
#>  3  1994 偏向統一       0.156
#>  4  1994 永遠維持現狀   0.098
#>  5  1994 偏向獨立       0.08 
#>  6  1994 儘快統一       0.044
#>  7  1994 儘快獨立       0.031
#>  8  1995 維持現狀再決定 0.248
#>  9  1995 無反應         0.263
#> 10  1995 偏向統一       0.194
#> # … with 193 more rows

從圖中可以看出,已經變成長表格了。不過,若分為五種類型,圖中將會有五條折線,呈現上可能不易比較,因此我們決定將相似的概念歸類,將偏向統一和儘快統一合併,也將偏向獨立和儘快獨立合併,這樣將會剩下三種,如此一來,圖中也只會剩下三條直線。

df_crossstraight_long2 <- df_crossstraight %>% 
  mutate(偏向或盡快獨立 = 偏向獨立 + 儘快獨立, 
         暫時或永遠維持現狀 = 維持現狀再決定 + 永遠維持現狀, 
         偏向或盡快統一 = 偏向統一 + 儘快統一) %>%
  select(year, matches("或")) %>%
  pivot_longer(cols = -1, names_to = "type", values_to = "n") %>%
  filter(!is.na(n)) %>%
  mutate(n = n/100)

df_crossstraight_long2
#> # A tibble: 87 × 3
#>     year type                   n
#>    <dbl> <chr>              <dbl>
#>  1  1994 偏向或盡快獨立     0.111
#>  2  1994 暫時或永遠維持現狀 0.483
#>  3  1994 偏向或盡快統一     0.2  
#>  4  1995 偏向或盡快獨立     0.116
#>  5  1995 暫時或永遠維持現狀 0.404
#>  6  1995 偏向或盡快統一     0.217
#>  7  1996 偏向或盡快獨立     0.136
#>  8  1996 暫時或永遠維持現狀 0.458
#>  9  1996 偏向或盡快統一     0.22 
#> 10  1997 偏向或盡快獨立     0.172
#> # … with 77 more rows

繪製折線圖

處理完資料後,我們可以開始利用  geom_line() 繪製折線圖。

這張圖想呈現的是台灣人對兩岸未來走向立場的時間變化,時間映射到x軸,對兩岸未來走向的立場映射到y軸,至於立場的三種類型,則會映射到顏色變數。

我們在 ggplot() 裡面代表美學(aesthetics)的aes()中放入年齡(year)作為x軸、立場的百分比(n)作為y軸,認同的類型(type)則填入color當中。

df_crossstraight_long2 %>% 
  mutate(year = as.Date(str_c(year, "/1/1"))) %>%
  filter(type != "無反應") %>%
  ggplot(aes(x = year, y = n, group = type, color = type)) +
  geom_line(size = 2) +
  theme(legend.position="none") +
  theme(panel.grid.major.x = element_line(colour = "gray", linetype = "dotted")) +
  theme(title = element_text(family = "Noto Sans TC Regular", size = 24),
        axis.text = element_text(family = "Noto Sans TC Regular", size = 18))

我們另外補上scale_x_date()scale_y_continuous(),讓圖表變得好看。

df_crossstraight_long2 %>% 
  mutate(year = as.Date(str_c(year, "/1/1"))) %>%
  filter(type != "無反應") %>%
  ggplot(aes(x = year, y = n, group = type, color = type)) +
  geom_line(size = 2) +
  scale_x_date(date_labels = "'%y", breaks = seq(as.Date("1994-01-01"), as.Date("2022-01-01"), by="2 year")) + #, expand=c(0.02,0)
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  theme(legend.position="none") +
  theme(panel.grid.major.x = element_line(colour = "gray", linetype = "dotted")) +
  theme(title = element_text(family = "Noto Sans TC Regular", size = 24),
        axis.text = element_text(family = "Noto Sans TC Regular", size = 18))

如果不喜歡預設的顏色,也可以自己指定,我們在這邊就指定三種顏色,接著用scale_color_manual()指派顏色。

value_crossstraight = c("偏向或盡快統一"="#E60000","偏向或盡快獨立"="#406A51","暫時或永遠維持現狀"="#FA9F42")

df_crossstraight_long2 %>% 
  mutate(year = as.Date(str_c(year, "/1/1"))) %>%
  filter(type != "無反應") %>%
  ggplot(aes(x = year, y = n, group = type, color = type)) +
  geom_line(size = 2) +
  scale_x_date(date_labels = "'%y", breaks = seq(as.Date("1994-01-01"), as.Date("2022-01-01"), by="2 year")) + #, expand=c(0.02,0)
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  scale_color_manual(values = value_crossstraight) +
  theme(legend.position="none") +
  theme(panel.grid.major.x = element_line(colour = "gray", linetype = "dotted")) +
  theme(title = element_text(family = "Noto Sans TC Regular", size = 24),
        axis.text = element_text(family = "Noto Sans TC Regular", size = 18))

之前的圖表好像都沒有加過文字,這次利用labs()加加看!

df_crossstraight_long2 %>% 
  mutate(year = as.Date(str_c(year, "/1/1"))) %>%
  filter(type != "無反應") %>%
  ggplot(aes(x = year, y = n, group = type, color = type)) +
  geom_line(size = 2) +
  scale_x_date(date_labels = "'%y", breaks = seq(as.Date("1994-01-01"), as.Date("2022-01-01"), by="2 year")) + #, expand=c(0.02,0)
  scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0,1)) +
  scale_color_manual(values = value_crossstraight) +
  labs(x= "年份\n",y= "百分比", 
       title = "偏向/盡快獨立佔30%,暫時/永遠維持現狀有57%",
       subtitle = "臺灣民眾統獨立場趨勢分佈, 1992 - 2022",
       caption = "資料來源:國立政治大學選舉研究中心重要政治態度分佈趨勢圖\n註:加總未滿 100% ,因有受訪者沒有提供答覆") +
  theme(legend.position="none") +
  theme(panel.grid.major.x = element_line(colour = "gray", linetype = "dotted")) +
  theme(title = element_text(family = "Noto Sans TC Regular", size = 24),
        axis.text = element_text(family = "Noto Sans TC Regular", size = 18))

小結

在這篇文章中,我們嘗試畫了一張折線圖(line chart),從繪圖的基本開始,一直到加上調整橫軸與縱軸的scale、加上顏色、補上標題等。希望你喜歡這篇文章,也能夠增添對於 ggplot2 的認識,並且學到東西。

5 Comments

  1. Avatar binance register
    2023-05-24 at 06:25 // Reply

    Thank you for your shening. I am worried that I lack creative ideas. It is your enticle that makes me full of hope. Thank you.

  2. I have read your article carefully and I agree with you very much. This has provided a great help for my thesis writing, and I will seriously improve it.

  3. The point of view of your article has taught me a lot, and I already know how to improve the paper, thank you.

  4. The point of view of your article has taught me a lot, and I already know how to improve the paper, thank you.

  5. Thanks for shening. I read many of your blog posts, cool, your blog is very good.

Leave a Reply