Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: color area between two crossbars

Tags:

r

colors

ggplot2

Is it possible to color only part of barchart in ggplot2?
I'd like the colored region between crossbars: "Mean daily maximum" and "Mean daily minimum". This is my data:

temperature <- read.table(text = 'X  1  2  3  4  5  6
                          1 "Highest temperature" 31 40 39 34 39 42
                          2 "Mean daily maximum" 27 34 32 30 34 35
                          3 "Mean daily minimum" 26 31 31 30 31 35
                          4 "Lowest temperature" 18 20 20 20 20 24', header =T)

t <- dcast(melt(temperature), variable~X)
ggplot(t, aes(x=variable,ymin = `Lowest temperature`, 
              ymax = `Highest temperature`, lower = `Lowest temperature`, 
              upper = `Highest temperature`, middle = `Mean daily maximum`)) + 
  geom_boxplot(stat = 'identity') +
  xlab('Number') + 
  ylab('Temperature') +
  geom_crossbar(aes(y = `Mean daily maximum` ))+
  geom_crossbar(aes(y = `Mean daily minimum`))
like image 545
erwi_k Avatar asked Apr 17 '26 20:04

erwi_k


1 Answers

library(ggplot2)
library(reshape2)

read.table(
  text = 'X  1  2  3  4  5  6
1 "Highest temperature" 31 40 39 34 39 42
2 "Mean daily maximum" 27 34 32 30 34 35
3 "Mean daily minimum" 26 31 31 30 31 35
4 "Lowest temperature" 18 20 20 20 20 24', 
  header = TRUE
) -> temperature

temp_long <- reshape2::dcast(reshape2::melt(temperature), variable~X)

ggplot(
  temp_long, 
  aes(
    x = variable,
    ymin = `Lowest temperature`, 
    ymax = `Highest temperature`, 
    lower = `Lowest temperature`, 
    upper = `Highest temperature`, 
    middle = `Mean daily maximum`
  )
) + 
  geom_boxplot(stat = 'identity') +
  geom_rect(
    aes(
      xmin = as.numeric(variable)+0.45, 
      xmax = as.numeric(variable)-0.45,
      ymin = `Mean daily minimum`,
      ymax = `Mean daily maximum`
    ),
    fill = "#a50f15"
  ) +
  geom_crossbar(aes(y = `Mean daily maximum` )) +
  geom_crossbar(aes(y = `Mean daily minimum`)) +
  labs(x = 'Number', y = 'Temperature')

enter image description here

like image 58
hrbrmstr Avatar answered Apr 19 '26 11:04

hrbrmstr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!