r/sparkline/win&loss/chnage bar colors

30 Views Asked by At

Working on a win/loss sparkline in R. Data coded 1 for win and -1 for loss. Can get basic structure with ggplot and following code:

puck <- data.frame(game=c("g1", "g2", "g3", "g4"),
                 wnls=c(-1, 1, -1, 1))
head (puck)
library(ggplot2)
# sparkline via barplot, v1
plot1<-ggplot(data=puck, aes(x=game, y=wnls)) +
     geom_bar(stat="identity", width=0.5)
plot1

Understand how to change all bars to one color. However, want to code the wins blue and losses red. Suggestions on how to do this? Thanks, RB

1

There are 1 best solutions below

4
TarJae On

One way is to define a new column with wins and losses and then map fill to aesthetics:

library(ggplot2)
library(dplyr)

# sparkline via barplot, v1
plot1<-ggplot(data=puck %>% 
                mutate(win_loss = ifelse(wnls < 0, "loss", "win")), 
              aes(x=game, y=wnls, fill = win_loss)) +
  geom_bar(stat="identity", width=0.5)+
  scale_fill_manual(values = c("red", "green"))
plot1

enter image description here