簡體   English   中英

R:使用 ggplot 在同一圖形上繪制多條線

[英]R: plotting multiple lines on same graph using ggplot

我有一個名為data的數據集,其中包含每年某些地區的人口,它看起來像這樣:

 Year   CityA CityB CityC
1 2005  3000  4000  2000
2 2006  4000  6000  3000
3 2007  5000  8000  7000
4 2008  6000  4000  5000
5 2009  7000  4000  9000
6 2010  8000  4000  6000
7 2011  9000  6000  7000

我想繪制CityACityBCityC因為在同一個圖線。

到目前為止我的代碼是:

data %>% gather(key = "City", value = "Population", -Year) %>%
  ggplot(aes(x = Year, y = `Population`) +
  geom_line()

但是,這不能正確繪制。 有人可以指出我做錯了什么嗎?

謝謝。

我們可以指定ggplot缺少的aescol (另外,the )

library(dplyr)
library(tidyr)
library(ggplot2)
data %>% 
  pivot_longer(cols = -Year, values_to = 'Population') %>%
  ggplot(aes(x = Year, y = Population, col = name)) + 
     geom_line()

在此處輸入圖片說明

數據

data <- structure(list(Year = 2005:2011, CityA = c(3000L, 4000L, 5000L, 
6000L, 7000L, 8000L, 9000L), CityB = c(4000L, 6000L, 8000L, 4000L, 
4000L, 4000L, 6000L), CityC = c(2000L, 3000L, 7000L, 5000L, 9000L, 
6000L, 7000L)), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7"))

暫無
暫無

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

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