Kai Mayer
Kai Mayer

Reputation: 207

colored 100% barplot with ggplot2

Ia am completly new to R and just absolved the introduction from edX. Unfortunately it doesn't teach anything about ggplot2, what i want to use for my graphs in my thesis. I want to get 100% bar plots with different colours and if possible the value in the according bar. my data looks like this:

Concentration,Percentage,Phenotype
Control,0.933333333,0
Control,0.014814815,1
Control,0.022222222,2
Control,0.02962963,3
0.002,0.918181818,0
0.002,0.018181818,1
0.002,0.018181818,2
0.002,0.045454545,3
0.02,0.930434783,0
0.02,0.017391304,1
0.02,0.017391304,2
0.02,0.034782609,3
0.2,0.928571429,0
0.2,0.032467532,1
0.2,0.012987013,2
0.2,0.025974026,3
2,0.859813084,0
2,0.028037383,1
2,0.046728972,2
2,0.065420561,3

and the code i used is this:

ggplot(Inj, aes(x=Concentration, y=Percentage, fill=Phenotype))+geom_bar(stat='identity',color='black')

The resulting graph looks like that:

enter image description here

how can i change the color of the different bars and get the %-values in the bars?

Thanks for any help

Upvotes: 0

Views: 626

Answers (2)

user6275647
user6275647

Reputation: 381

You can use scale_x_discrete to re-order the factors manually like this:

ggplot(Inj, aes(x=Concentration, y=Percentage, fill=Phenotype)) + 
  geom_bar(stat='identity',color='black') +
  scale_fill_grey(start = .4, end = .9) + 
  theme_bw()+ylab("Distribution") + 
  xlab("Contentration [mg/ml]") + 
  ggtitle("Dose-respond analysis") +
  theme(legend.title = element_text(colour="black", size=10, face="bold")) +
  theme(legend.background = element_rect(fill="white",
                                   size=0.5, linetype="solid", 
                                   colour ="black")) +
  scale_x_discrete(limits=c('Control','0.002', '0.02', '0.2', '2'),
                   labels=c('Control\n(N=000)',
                            '0.002\n(N=000)', 
                            '0.02\n(N=000)', 
                            '0.2\n(N=000)', 
                            '2\n(N=000)'))

I added the labels part to scale_x_discrete in response to your question in the comments below. You just need to update the N values. Notice that I put \n in each label in order to force the label text on to two lines so it wouldn't be jumbled. Just remove the \n if you'd prefer it to be on a single line.

Upvotes: 0

jalapic
jalapic

Reputation: 14212

You can make the colors controllable by making your fill variable a factor. Then you can manually adjust the colors like this

ggplot(Inj, aes(x=Concentration, y=Percentage, fill=factor(Phenotype)))+geom_bar(stat='identity',color='black') +
  scale_fill_manual(values=c("red", "blue", "yellow", "pink"))

enter image description here

I don't recommend putting the values over the colors as they won't be visible for the very small values. I would use another way to visualize the data.

Upvotes: 1

Related Questions