2016-10-02 104 views
1

我有以下數據框:結合堆積條形和線條到同一個圖形與分類變量

library(rsdmx) 
library(dplyr) 
library(countrycode) 

dt<-as.data.frame(readSDMX("http://widukind-api.cepremap.org/api/v1/sdmx/IMF/data/IFS/..Q.BFPA-BP6-USD")) 
AP<-rename(dt, Country=WIDUKIND_NAME, Year=TIME_PERIOD,A.PI.T=OBS_VALUE)  
AP<-AP[c("Country","REF-AREA","Year","A.PI.T")] 
AP$Country<-countrycode(AP$`REF-AREA`, "imf","iso3c") 
AP$A.PI.T<-as.numeric((as.character(AP$A.PI.T))) 
AP$Country[which(AP$`REF-AREA` == 163)] <- "EURO" 
AP$Country[which(AP$`REF-AREA` == 967)] <- "RKS" 
AP$Country[which(AP$`REF-AREA` == 355)] <- "CUW+SMX" 
AP$Country<-as.factor(AP$Country) 
AP$v1<-AP$A.PI.T/2 
AP$v2<-AP$v1 

str(AP) 

'data.frame': 11452 obs. of 6 variables: 
$ Country : Factor w/ 142 levels "ABW","AFG","ALB",..: 2 2 2 2 2 2 2 2 2 2 ... 
$ REF-AREA: Factor w/ 142 levels "512","299","258",..: 1 1 1 1 1 1 1 1 1 1 ... 
$ Year : chr "2008-Q2" "2008-Q3" "2008-Q4" "2009-Q1" ... 
$ A.PI.T : num -113146 -321591 -1000741 16685590 540591 ... 
$ v1  : num -56573 -160796 -500370 8342795 270295 ... 
$ v2  : num -56573 -160796 -500370 8342795 270295 ... 

正如你看到的,我有三個數值變量和其他變量Year應該拍攝日期。同時,有一個分類變量Country

我的範圍是爲Country中的每個類別創建圖表。

我想要的圖表類型是堆疊酒吧和線型圖表的混合,我想要一個選項來預先指定日期範圍,例如我想從2012年Q1到2015年3月。爲了讓您的圖表看起來應該是個更好的主意,我在Country

enter image description here

在理想的情況下,的確在Excel中的例子,對於Euro,我想導出應該是所有圖表將Country中的每個級別都創建爲非R用戶可以使用和探索的便捷表單。

回答

0

你想要的東西,像下面的(僅適用於歐元和UKR所示):

library(reshape2) 
df <- melt(AP, id=1:3) 
library(ggplot2) 
ggplot(df[df$Country %in% c('EURO', 'UKR'),], aes(Year, value, fill=variable)) + 
    geom_bar(stat='identity') + 
    theme(axis.text.x = element_text(angle=90, vjust = 0.5)) + 
    facet_wrap(~Country, scales='free') 

enter image description here

+0

是的,但添加的行中的圖片,並指定範圍內的日期重要。 – msh855