2017-07-07 15 views
0

エクスポートとインポートの両方をプロットし、netexportsが正であるかどうかに応じて2つの系列の差を色分けすることによって、netexports(exports-または負である。geom_ribbon(ggplot2)を使用して、2つの時系列の違いを色の変化とプロットする

library(tidyverse) 

data <- tribble(
    ~year, ~exports, ~imports, 
    #--|--|---- 
    2003, 3, 3.6, 
    2004, 4, 8.5, 
    2005, 7, 7, 
    2006, 9, 7, 
    2007, 15, 9, 
    2008, 17, 12, 
    2009, 7, 8, 
    2010, 8, 7, 
    2011, 8, 8, 
    2012, 7, 9, 
    2013, 2, 11, 
    2014, 9, 13, 
    2015, 5, 15 
) 

ggplot(data, aes(x = year)) + 
    geom_ribbon(aes(ymin = imports, ymax = exports)) 

これは、私を取得します:

enter image description here

シリーズとの違いですでに色が、より高いである1を私に教えてくれないRを使用して

。私が試した

次へ:

ggplot(data, aes(x = year)) + 
    geom_ribbon(aes(ymin = imports, ymax = exports, fill = exports > imports)) 

得られます

enter image description here

しかし、ここで何かを間違ってがあるようですし、私はそれが何であるかわかりません。

答えて

1

これは近づきますが、値が等しいポイントに行がない場合でも失敗します。あなたのニーズに応じて、2008年と2009年の間のポイントを計算し、それをあなたのデータセットに人工的に追加することができます。

data$minval <- pmin(data$imports, data$exports) 

ggplot(data, aes(x = year)) + 
    geom_ribbon(aes(ymin = minval, ymax = exports), fill = "blue") + 
    geom_ribbon(aes(ymin = minval, ymax = imports), fill = "red") 
+1

ニースが解決しました。 gomplot(data、aes(x = year))+ geom_ribbon(aes(ymin = pmin(輸入、輸出)、ymax =輸出)、塗りつぶし= "青")+ geom_ribbon (aes(ymin = pmin(輸入、輸出)、ymax =輸入)、塗りつぶし= "赤") –

関連する問題