rggplot2groupingaestheticsggpattern

How to order fills colors of a barplot while using groups


I would to use a "Device" column to fill in a same order two different figures (Fig1 and Fig2 bellow). However, when I dispatch my data in two groups for Fig2, the factor order of the Device column is not maintained and I don't understand why.

Sample data

data1

System   Device    C       mFP       uFP
CC       A         6.70    9.11      455.70
CC       B         0.02    308.73    1.03
CC       C         6.65    2142.00   452.53

data2

System   Device  Type   Value
CC       A       mFP    9.11
CC       A       uFP    455.70
CC       B       mFP    308.73
CC       B       uFP    1.03
CC       C       mFP    2142.00
CC       C       uFP    452.53

For each data file, Device is a factor with levels. cbPalette contains a vector of hex colors.

Sample code and associated figures

Fig1

Fig1 <- ggplot(data1, aes(x=System, y=C,fill=Device)) +geom_bar(width=0.5, stat='identity', colour= 'black') +scale_fill_manual(values = cbPalette)

Fig1

Fig2

Fig2 <- ggplot(data2, aes(x=System, y=Value, fill=Device)) +geom_bar_pattern(aes(group=Type, pattern=Type),stat="identity",width=0.5,pattern_fill = "black",colour= 'black',pattern_density = 0.1,pattern_spacing = 0.025,pattern_key_scale_factor = 0.6)+scale_pattern_manual("type", limits=c("uFP", "mFP"),scale_fill_manual(values = cbPalette)

Fig2

Order of devices is reversed compared to figure 1

When I don’t use group for Fig2, devices are displayed in the same order than Fig1.
 I want devices displayed in the same order than Fig1, within each group (uFP and mFP).

I try to use factors with levels and arrange the data before plotting figure 2 but when using the group argument, the order in not maintained. I expect my figure to display the fill data in the same order for Fig2 than Fig1.


Solution

  • It works properly when "group" is deleted.