Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bar chart - Assign colors to negative and positive values in R barplot

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.

enter image description here

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: enter image description here

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'))

enter image description here

Any help would be very appreciated, thanks!

question from:https://stackoverflow.com/questions/65882921/assign-colors-to-negative-and-positive-values-in-r-barplot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The appear to be invisible due to the black borders and because they are many, just switch them off.

barplot(height=NPGO$index, col=ifelse(NPGO$index > 0, 2, 4), border=NA)

enter image description here


Data:

d <- read.csv("http://www.o3d.org/npgo/npgo.php", skip=29)[-(848:850),]
NPGO <- as.data.frame(`colnames<-`(type.convert(do.call(rbind, strsplit(d, "\s+"))[,-1]),
              c("year", "month", "index")))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...