ggplot2(R)不会绘制多列

时间:2019-10-15 23:44:19

标签: r ggplot2

我正在尝试使用ggplot2绘制不同的系列(列)。但是我似乎无法绘制剧情。

这是我的数据的样子(从1976年到2017年)。

Year     Atlantic     Prairie   Ter   Ontario       BC        Quebec      Canada

1976    1.2638857   0.4546927   NA   0.6815441  0.7264928   1.0050021   0.8424173
1977    1.1722437   0.4819217   NA   0.5951699  0.7264113   0.8883986   0.7701221
1978    1.1990781   0.4870121   NA   0.5737307  0.7684976   0.8672100   0.7604538
1979    1.1287050   0.4333563   NA   0.5194313  0.6579418   0.8407571   0.7086144
1980    1.1133467   0.4198007   NA   0.5313260  0.5992944   0.7677071   0.6745683

这是我从类似的问题中得到的代码。

library("reshape2")
coverage <- read.xlsx(. . .)
Tall_data <- melt(coverage ,  id.vars = "Year", variable.name = "series") #Step1: Rearrange data in tall format
ggplot(Tall_data, aes(Year,value)) + geom_line(aes(colour = series)) #Step2: Plot

在步骤1中,R给我“度量值变量之间的属性不相同;它们将被删除”

我已经附上了制作的剧情-这很奇怪。

请注意,“领土”列中的某些数据为NA(从1976年到2003年)。

我知道我可以这样:

ggplot(coverage, aes(Year)) + 

  labs(y= "The B/U Ratio") +
  geom_line(aes(y=Atlantic_Provinces), colour="green") +
  geom_line(aes(y=Prairie_Provinces), colour="red") + ...

但是我希望能够用一个命令来完成。此外,单独进行操作并不会给我提供图例名称。我研究了其他R指南,这些指南或多或少暗示了我所使用的相同代码。但是由于某种原因,它对我不起作用。

以下是两个类似的帖子:

Plot multiple columns on the same graph in R

How to plot all the columns of a data frame in R-这是我所关注的。

enter image description here

1 个答案:

答案 0 :(得分:1)

这是正确的方向吗?

dat <-
"Year     Atlantic     Prairie   Ter   Ontario       BC        Quebec      Canada
1976    1.2638857   0.4546927   NA   0.6815441  0.7264928   1.0050021   0.8424173
1977    1.1722437   0.4819217   NA   0.5951699  0.7264113   0.8883986   0.7701221
1978    1.1990781   0.4870121   NA   0.5737307  0.7684976   0.8672100   0.7604538
1979    1.1287050   0.4333563   NA   0.5194313  0.6579418   0.8407571   0.7086144
1980    1.1133467   0.4198007   NA   0.5313260  0.5992944   0.7677071   0.6745683
"
df <- read.delim(textConnection(dat), sep="")
library(tidyverse)
tall_df <- pivot_longer(df, 
            cols = c("Atlantic", "Prairie", "Ter", "Ontario", "BC", "Quebec", "Canada"),  
            names_to = "region"  
            )
ggplot(tall_df, aes(x = Year, y = value, color=region)) +
  geom_line()

enter image description here