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!
question from:
https://stackoverflow.com/questions/65882921/assign-colors-to-negative-and-positive-values-in-r-barplot 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…