f4b
f4b

Reputation: 13

Grouped ggplot bars with a gradient color dependent on another variable

My dataset includes values for 'left' and 'right' of 8 (4x2) observations. Like this TEST frame:

Labels        r         pval      Mean  Side
L1 0.49425792 1.191802e-04 0.7992786  Left
L2 0.25906498 3.371854e-02 1.7977923  Left
L3 0.63098789 3.711588e-07 0.8519239  Left
L4 0.20325181 7.707517e-02 1.1287030  Left
L1 0.72761384 7.991909e-10 1.1369230  Right
L2 0.93941231 0.000000e+00 1.0262915  Right
L3 0.80899301 3.805845e-13 1.1670454  Right
L4 0.30345181 7.507517e-02 1.1677030  Right

and I can create a grouped plot doing:

ggplot(data = TEST, aes(factor(Labels),r, fill=Side)) + 
geom_bar(stat="identity", position = "dodge") 

The plot is very nice and I can see 'Left/Right' grouped for each label. However, I would like to use a gradient color to fill each bar using the values in 'Mean', keeping the grouped 'Left/Right' bars.

Is it possible to do that? Thank you, Fab

Upvotes: 1

Views: 2441

Answers (1)

erc
erc

Reputation: 10131

You can add a group statement based on Side and specify fill according to Mean:

ggplot(data = TEST, aes(factor(Labels),r, group=Side, fill=Mean)) + 
  geom_bar(stat="identity", position = "dodge")

If you want to change the colours you can add scale_fill_gradient(), e.g.

scale_fill_gradient(low="blue", high="red")

enter image description here

Upvotes: 1

Related Questions