I'm looking to make a stacked barchart with colors representing values from a separate data column as well as add an accurate color bar using just the base graphics in R. There is one other post about this but it is pretty disorganized and in the end doesn't help me answer my question.
# create reproducible data
d <- read.csv(text='Day,Location,Length,Amount
1,4,3,1.1
1,3,1,.32
1,2,3,2.3
1,1,3,1.1
2,0,0,0
3,3,3,1.8
3,2,1,3.54
3,1,3,1.1',header=T)
# colors will be based on values in the Amount column
v1 <- d$Amount
# make some colors based on Amount - normalized
z <- v1/max(v1)*1000
colrs <- colorRampPalette(c('lightblue','blue','black'))(1000)[z]
# create a 2d table of the data needed for plotting
tab <- xtabs(Length ~ Location + Day, d)
# create a stacked bar plot
barplot(tab,col=colrs,space=0)
# create a color bar
plotr::color.bar
This for sure produces a color coded stacked bar graph, but the colors do not represent the data accurately.
For Day 1, Locations 4 and 1 should be identical in color. Another example, the first and last entries in the Amount column are identical, but color of the top of the left column doesn't match the bottom of the right column.
Also, I found how to make a color bar on a different post and it uses the plotr::color.bar
code, but plotr
apparently isn't a package and I'm not sure how to carry on.
How can I get the colors to match the appropriate section and add an accurate color bar?