I'm trying to replicate a time series barplot figure of a climate index (NPO, specifically) where there are different colors for positive and negative values.
I'm using a different index, so the values are different but the concept is the same. the data are here (I don't know how to link a dataset you can import? Sorry for the inconvenience)
I've attempted ggplot and the zoo package to restructure the data:
library(tidyverse)
library(here)
library(zoo)
NPGO <- read_csv(here('data//NPGOindex_toJuly2020.csv'))
NPGO <- rename(NPGO, index=`NPGO index`)
glimpse(NPGO)
NPGO$DATE <- as.yearmon(paste(NPGO$YEAR, NPGO$MONTH), '%Y %m')
NPGO$color <- ifelse(NPGO$index<0, 'negative','positive')
ggplot(NPGO, aes(x=DATE, y=index)) +
geom_bar(stat='identity',
width=0.8, aes(fill=color)) +
scale_x_yearmon(format='%m %Y', expand=c(0,0)) +
scale_fill_manual(values=c(positive='red',negative='blue')) +
geom_line(aes(y=0), color='black') + theme_bw()
Though I end up with these stacked bars, not sequential:
base barplot()
produces more what I am looking for and I attempted to use the code that seemingly answered my question, but no dice:
barplot(height=NPGO$index,
col=ifelse(NPGO$index>0,'red','blue'))
Any help would be very appreciated, thanks!
The appear to be invisible due to the black border
s and because they are many, just switch them off.
barplot(height=NPGO$index, col=ifelse(NPGO$index > 0, 2, 4), border=NA)
We also can consider two breaks instead of one, e.g. -2 and 2.
with(NPGO, barplot(height=index, col=ifelse(index < -2, 4, ifelse(index > 2, 2, 8)), border=NA))
Data:
d <- read.csv("http://www.o3d.org/npgo/npgo.php", skip=29)[-(848:850),]
NPGO <- do.call(rbind, strsplit(d, "\\s+"))[,-1] |>
apply(1, as.numeric) |> t() |> as.data.frame() |> setNames(c("year", "month", "index"))