ggplot2:Aesthetics中的几个图表必须是长度为1或相同的长度

时间:2014-11-11 11:29:56

标签: r graph ggplot2

我使用以下数据集(可下载的here)和代码(下面的代码)尝试在一个ggplot中绘制几个图。我知道那里有很多解释,但我似乎还没有完成工作,因为我很困惑在哪里把ggplot的命令放到了解我想要的地方。

此外,我知道有两种方式可以存在原始数据:无论是宽格式还是长格式。当我以宽格式保存数据时,为了完成工作,我必须写很多东西(参见下面的代码和图表),但是当我将其转换为长格式时,ggplot抱怨缺少值(请参阅下面的代码和错误消息)。

这是我的最小代码示例:

library(ggplot2) # for professional graphs
library(reshape2) # to convert data to long format

WDI_GDP_annual <- WDI[which(WDI$Series.Name=='GDP growth (annual %)'),] # extract data I need from dataset
WDI_GDP_annual_short <- WDI_GDP_annual[c(-1,-2,-4)] # wide format
test_data_long <- melt(WDI_GDP_annual_short, id = "Time") # long format

# (only successful) graph with wide format data
ggplot(WDI_GDP_annual_short, aes(x = Time)) +
 geom_line(aes(y = Brazil..BRA., colour = "Brazil..BRA.", group=1)) +
 geom_line(aes(y = China..CHN., colour = "China..CHN.", group=1)) +
 theme(legend.title = element_blank())

# several graphs possibilities to plot data in long format and to have to write less (but all complain)
ggplot(data=test_data_long, aes(x = time, y = value, colour = variable)) +
 geom_line() +
 theme(legend.title = element_blank())

ggplot(data=test_data_long, aes(x = time, y = value, color = factor(variable))) +
 geom_line() +
 theme(legend.title = element_blank())

ggplot(test_data_long, aes(x = time, y = value, colour = variable, group = variable)) +       
 geom_line()

这是我迄今为止(唯一)成功的情节,但我不想写这么多(因为我想在这个ggplot中再增加6个图表):

enter image description here

我知道使用他的长格式将意味着更优雅的方式如何绘制多重绘图,但我使用的命令(见上文)我总是得到以下抱怨:

  

错误:美学必须是长度1或与长度相同   dataProblems:时间

有人知道我的问题的答案吗?

1 个答案:

答案 0 :(得分:4)

首先:您的数据在所谓的数字列中包含字符串“..”,这会将整列转换为class character(或factor,具体取决于您的{ {1}}设置)。

如果您希望将“..”视为stringsAsFactors,请将NA添加到na.strings = ".."来电。这将确保将列视为read.xxx。在您阅读完任何数据集后,numeric应该是您的朋友。

str

enter image description here