Display negative values in the first quarter of a bar chart but with different bar color than the positive values

Viewed 80

I create a bar plot using ggplot in combination with plotly and I would like to know if there is a way to display the negative values above the x-axis as positive but with a different color (red) than the blue and also a legend that would clarify that blue are the positive values and red the negatives. Something like:

enter image description here

date<-c(as.Date("2020-09-15", "%Y-%m-%d"),as.Date("2020-09-14", "%Y-%m-%d"),
        as.Date("2020-09-13", "%Y-%m-%d"),as.Date("2020-09-12", "%Y-%m-%d"),
        as.Date("2020-09-15", "%Y-%m-%d"),as.Date("2020-09-14", "%Y-%m-%d"),
        as.Date("2020-09-13", "%Y-%m-%d"),as.Date("2020-09-12", "%Y-%m-%d"))
value<-c(5,6,7,8,-3,-5,6,8)
df<-data.frame(date,value)

# Minimal theme + blue fill color
p<-ggplot(data=df, aes(x=date, y=value)) +
  geom_bar(stat="identity", fill="steelblue")+
  theme_minimal()+ labs(x = "Date of Specimen Collection",y="Total Tests per Day")
ggplotly(p)
1 Answers

something along these lines?

df <- df %>% 
  mutate(pos_neg = if_else(value > 0, "Positive", "Negative"))
# Minimal theme + blue fill color
p<-ggplot(data=df, aes(x=date, y=abs(value), fill = pos_neg)) +
  geom_bar(position = "dodge", stat="identity")+
  scale_fill_manual(values=c("red","steelblue")) +
  theme_minimal()+ labs(x = "Date of Specimen Collection",y="Total Tests per Day")
ggplotly(p)

Another Option:

p1 <- ggplot(data=df) +
  geom_bar(data = filter(df, pos_neg == "Positive"), aes(x=date, y=abs(value)), position = "stack", stat="identity", fill = "steelblue")+
  geom_bar(data = filter(df, pos_neg == "Negative"), aes(x=date, y=abs(value)), position = "stack", stat="identity", fill = "red")
ggplotly(p1)

UPDATE TO OPTION 2: To get the legend labels and colours fill has to be in the aes.

colours <- c("Positive" = "steelblue", "Negative" = "red")

p1 <- ggplot(data=df) +
  geom_bar(data = filter(df, pos_neg == "Positive"), aes(x=date, y=abs(value), fill = pos_neg), position = "stack", stat="identity")+
  geom_bar(data = filter(df, pos_neg == "Negative"), aes(x=date, y=abs(value), fill = pos_neg), position = "stack", stat="identity")+
  scale_fill_manual(values = colours, name = "Positive/Negative") +
  # scale_fill_manual(values = c("Positive" = "steelblue", "Negative" = "red"), name = "Positive/Negative") + #another way to achieve colours
  labs(x = "Date of Specimen Collection",y="Total Tests per Day") +
  theme_minimal()

ggplotly(p1)


I can tidy this up with an update if it is looking correct

Related