Home > Back-end >  How to customize individual colours on graph in R?
How to customize individual colours on graph in R?

Time:03-13

I am currently trying to make a graph of a matrix where it graphs the second part on top of the first part i.e. 600 would be put on 9400 and then 500 over 9500 etc. While I have easily been able to do that, I am currently struggling with figuring out the colour formatting. I want the colours set in col to reflect the colours seen on the graph, however, I currently only see the first two colours only (green and blue). My code is below.

max.temp <- c(9400, 9500, 9600, 9800, 600, 500, 400, 200)
max.temp1 <- matrix(max.temp, nrow = 2, byrow = TRUE)

barplot(max.temp1, col = c("green", "blue", "red", "yellow", "black", "black", "black", "black"))

CodePudding user response:

It might be easier to switch to ggplot2 graphics than the base graphics package.

max.temp <- c(9400, 9500, 9600, 9800, 600, 500, 400, 200)
df <- data.frame(id=1:4, max.temp, col=c("green", "blue", "red", "yellow", "black", "black", "black", "black"))

library(ggplot2)
ggplot(df, aes(x=id, y=max.temp, fill=col))  
   geom_col()  
   scale_fill_identity()

enter image description here

  •  Tags:  
  • r
  • Related