Colouring and shading/texture of bars according to

2019-06-02 02:58发布

问题:

This question already has an answer here:

  • How to add texture to fill colors in ggplot2 5 answers

I am trying to make a bar plot like where, as with the example data and script below, a measurement is taken from 4 individuals say before and after giving a treatment. Sorry, I don't have enough reputation to upload an example picture.

I would like to plot the individuals by a certain colour (e.g. Tom as green, Fred red, etc) but then for the bars representing the treatment I would like to add diagonal lines on top of the colour to indicate treatment.

Is this possible easily? The code below I have adapted from: Generate ggplot2 boxplot with different colours for multiple groups

Many thanks in advance for any suggestions. I hope what I'd like to do makes sense.

Example data (sorry, not sure how to upload it so imported from .csv):

Name,Time,Dose,Variable,n,Mean,SD,Median,Upper.SEM,Lower.SEM
Ted,1,0,P,3,20.1341,1.049791,20,0.5728394,0.5569923
Fred,1,0,P,3,38.63702,1.042969,37.74,0.9499892,0.9271918
Tom,6,0,P,3,42.3231,1.073583,43.75,1.7710033,1.6998725
Peter,6,0,P,3,36.01035,1.208213,35.63,4.1551262,3.7252776
Ted,1,1,P,3,22.79528,1.110182,21.64,1.4179833,1.334943
Fred,1,1,P,3,24.25966,1.156925,23.82,2.1300073,1.9580866
Tom,6,1,P,3,13.78995,1.170568,13.15,1.3126463,1.1985573
Peter,6,1,P,3,23.3236,1.4403,20.65,5.4688355,4.4300848

And code I have been using:

g<- ggplot(example, aes(x=Name, y=Mean,fill=interaction(Name,Dose) ))
g<-g + geom_bar(stat="identity", position="dodge") 
g<-g + geom_errorbar(aes(ymax=Mean+Upper.SEM, ymin=Mean-Lower.SEM),       position=position_dodge(0.9), width=0.5)
g<- g+ scale_fill_manual(values=c("green","green","red","red","green","green","red","red"
                    ))
g

回答1:

You seem to want to use textures, and as the link in @Henrik's comment explains, that's not possible in ggplot. One possible work-around is to use different colors for the names, and different shades of color for the doses.

library(ggplot2)
library(RColorBrewer)
categories         <- aggregate(Dose~Name,example,function(x)length(unique(x)))  # number of sub-category for each category
category.palettes  <- c("Purples","Reds","Greens","Blues")
colors <- unlist(lapply(1:nrow(categories),
                        function(i){colorRampPalette(brewer.pal(9,category.palettes[i])[3:7])(categories[i,2])}))
names <- sort(unique(example$Name))

g <- ggplot(example, aes(x=Name, y=Mean,fill=interaction(Dose,Name) ))
g <- g + geom_bar(stat="identity", position="dodge") 
g <- g + geom_errorbar(aes(ymax=Mean+Upper.SEM, ymin=Mean-Lower.SEM), position=position_dodge(0.9), width=0.5)
g <- g+ scale_fill_manual("Subject", values=colors, breaks=paste0("1.",names),labels=names)
g


标签: r ggplot2