2

I have been using a consistent colour scheme across multiple bar plots using data from different data frames that share a common variable. This approach was based on an answer to this question. In each of these cases I was looking at one variable.

What I would like to do now is look at two variables on the same plot keeping the colour scheme consistent. It should look something like the following except the two bars for A should be the same colour (the first in the palette), the two bars for B should be the same colour (the second in the palette), etc. enter image description here

Sample data:

mydata <- data.frame( "Channel" = LETTERS[1:11], 
                  "V1" = seq(1100, 100, -100), 
                  "V2"= seq(110, 10, -10) )

and code for the above plot:

barplot(t(mydata[,2:3]), beside=T, 
    col=brewer.pal(11, "RdGy"), 
    names.arg=LETTERS[1:11])

I have been trying to do this in ggplot (which is my preference) but haven't succeeded. I have used the package reshape2 to melt the data and then use fill but that only gets me two colours. I have also tried using position='dodge' in various ways with no luck. I can get to a similar end result combining a bar plot and a line graph for the second variable but would prefer the double bar plot.

I would also prefer to stick with ggplot but any solution would be appreciated.

Community
  • 1
  • 1
pentandrous
  • 858
  • 1
  • 9
  • 18

2 Answers2

2

I solved it using a little hack. I set the color aesthetic to Channel and family to variables. The second one prevents that both values with the same Channel are plotted on top of each other when using position = "dodge".

library(ggplot2)
library(reshape2)
library(dplyr)

mydata <- data.frame( "Channel" = LETTERS[1:11], 
                      "V1" = seq(1100, 100, -100), 
                      "V2"= seq(110, 10, -10) )

df <- mydata %>% 
      melt(id = c("Channel"))

ggplot(df, aes(x = Channel, y = value, fill = Channel, family = variable)) + 
  geom_bar(stat = "identity", position = "dodge", color = "black") + 
  scale_fill_brewer(palette = "RdGy")

enter image description here

If you do not like the background you could use another theme. For example theme_base() from the ggthemes package should look similar to your barplot,

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alex
  • 4,925
  • 2
  • 32
  • 48
1

You can use base graphics by specifying the colours to be repeated for each adjacent bar.

barplot(t(mydata[,2:3]), beside=T, col=rep(brewer.pal(11, "RdGy"), each=2), names.arg=LETTERS[1:11])

enter image description here

dww
  • 30,425
  • 5
  • 68
  • 111