我使用以下数据集(可下载的here)和代码(下面的代码)试图在一个ggplot中绘制几个图 . 我知道那里有很多解释,但我似乎还没有完成工作,因为我很困惑在哪里把ggplot的命令放到了解我想要的东西 .
此外,我知道有两种方式可以存在原始数据:无论是宽格式还是长格式 . 当我将数据保存在 wide format 时,为了完成工作,我必须写很多东西(参见下面的代码和图表),但当我将其转换为 long format 时,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个图形):
我知道使用他的长格式将意味着更优雅的方式如何绘制多重绘图,但我使用的命令(见上文)我总是得到以下抱怨:
错误:美学必须是长度为1或与dataProblems:time相同的长度
有人知道我的问题的答案吗?
1 回答
首先:您的数据在所谓的数字列中包含字符串"..",它会将整列转换为
class
character
(或factor
,具体取决于您的stringsAsFactors
设置) .如果您希望将".."视为
NA
,请将na.strings = ".."
添加到您的read.xxx
电话中 . 这将确保将列视为numeric
. 阅读任何数据集后,str
应该是您的朋友 .