user15556454
user15556454

Reputation: 21

How to make SPI plots using ggplot2?

This is my first question on this platform, though I have thoroughly used it to solve many problems in R programming.

(1) I am stuck with SPI plots. The current SPI plot from SPEI package does not allow nice plots and I am not able to add the years along the x-axis. Kindly if anyone can help me to solve it.

(2) I have reworked the SPI data and created a data frame for different stations. However, when I use ggplot to make a similar plot as in (1), the chart is totally different. It appears that ggplot is not plotting the data continuously.

> head(s1)
  year month  rrP   rrV  rrPp   rrL   rrR   rrM   rrF  rrBC   rrA rrStM
1 1971     1 0.34  0.81  0.97  0.36  1.06  0.87  0.87  0.53  0.77  0.15
2 1971     2 0.80  1.96  1.07  0.64  1.59  1.29  0.85  0.66  1.76  0.96

3 1971 3 0.42 -0.43 -0.34 -0.46 -0.38 -0.01 0.04 -0.02 -0.46 -0.18 4 1971 4 0.65 0.93 1.69 1.83 0.82 1.54 1.02 0.94 0.64 0.68 5 1971 5 0.48 0.66 1.24 1.04 0.83 1.17 0.88 1.08 -0.45 -0.23 6 1971 6 0.19 -0.90 -0.75 -0.46 -1.25 -1.24 -0.46 -0.10 -0.50 -0.18 '''

Plot I obtained using the code below enter image description here

s1<-data.frame (s1)
s1 = as.data.table(s1)
ggplot(data = s1, aes(x = year, y = rrP)) +
geom_col(data = s1[Mau <= 0], fill = "red") +
geom_col(data = s1[Mau >= 0], fill = "blue") +
theme_bw()

I am looking to plot figures like this

enter image description here

Thanking you in advance for your replies. Vimal

Upvotes: 0

Views: 1558

Answers (1)

UseR10085
UseR10085

Reputation: 8198

To have years in x-axis, you have to convert the data into ts() object like the following code

library(SPEI)
data(wichita) 
#calculate 6-month SPI
plot(spi(ts(wichita$PRCP,freq=12,start=c(1980,1)),scale = 6))

enter image description here

Or you can follow this question How to format the x-axis of the hard coded plotting function of SPEI package in R?

Upvotes: 0

Related Questions