見出し画像

ggplot histogram VIX vs. SPX 日次収益率 cut scale_fill

概要

  • VIXの値と該当日のS&P500日次収益率の頻度分布を示す。

  • VIXの値は20を境に切り分けを行う。

  • 切り分けにはcut関数を使用した。

  • ヒストグラムを両者をレイヤーを重ねて表示している。

cut関数

cut(df$vix,breaks=c(min(df$vix),20,max(df$vix)),labels=c('l','h'),include.lowest = T)
breaksで分割範囲と分割点を選ぶ。ここでは最大値、20、最小値を指定して20を区切りに分割している。
labelsで分割範囲の区切り以下を'l'、それより上を'h'に指定している。
right = FALSE  を指定することで分割範囲の区切り未満を'l'、それ以上を'h'に指定できる。

サンプルコード

m <- merge(dailyReturn(GSPC)["2021::"], dailyReturn(VIX)["2020::"][index(dailyReturn(GSPC)["2021::"])], VIX[,4][index(dailyReturn(GSPC)["2021::"])])
colnames(m) <- c('spx','vixdiff','vix')
df <- m
df <- as.data.frame(df)
df <- cbind(df,l=cut(df$vix,breaks=c(min(df$vix),20,max(df$vix)),labels=c('l','h'),include.lowest = T))
p <- ggplot(df, aes(x=spx,fill=l))
p <- p + geom_histogram(bins=50,position = "identity", alpha = 0.5)
# p <- p + scale_fill_brewer(palette="Spectral",name="VIX",label=c("less than 20","eq or more than 20"))
p <- p + scale_fill_hue(name='VIX',label=c("eq or less than 20","more than 20"))
plot(p)

出力例

サンプルその2 三分割パターン

m <- merge(dailyReturn(GSPC)["2021::"], dailyReturn(VIX)["2020::"][index(dailyReturn(GSPC)["2021::"])], VIX[,4][index(dailyReturn(GSPC)["2021::"])])
colnames(m) <- c('spx','vixdiff','vix')
df <- m
df <- as.data.frame(df)
df <- cbind(df,l=cut(df$vix,breaks=c(min(df$vix),20,30,max(df$vix)),labels=c('l','m','h'),include.lowest = T))
p <- ggplot(df, aes(x=spx,fill=l))
p <- p + geom_histogram(bins=50,position = "identity", alpha = 0.5)
# p <- p + scale_fill_brewer(palette="Spectral",name="VIX",label=c("less than 20","eq or more than 20"))
p <- p + scale_fill_hue(name='VIX',label=c("eq or less than 20","more than 20","more than 30"  ))
plot(p)

この記事が気に入ったらサポートをしてみませんか?