1

New to R, stuck googling this (probably easy) thing for too long.

I want to plot the proportion of males that fathered offspring, according to whether they have a nest or not. (I don't want the information of how many offspring they fathered). This is my dataset called "males"

fishID nest off
fish1    1  25
fish2    0   0
fish3    0   5
fish4    1  15
fish5    1   0
fish6    0   2
fish7    0   0
fish8    1   4

I've used the following code to change the values of offspring to 0 and 1 (though this feels clumsy already)...

#converts the values in offspring to 0 and 1s
vars=c("off")
males[males$off != "0", vars]="1"
males 

...and I can plot proportions using...

ggplot(males,aes(x = males$nest,fill = males$off)) + 
geom_bar(position = "fill")

...but I would like to colour them so that 0 (no nest) is one colour and 1 (nest) is another colour, then the proportion of males that didn't father offspring is a paler version of each colour. The above produces colours according to "offspring", irrespective of "nest".

Tips welcome. (Mac OS X, R 3.0.3 GUI 1.63 Snow Leopard build (6660))

2
  • males$off <- factor(as.numeric(males$off != 0)) Commented Mar 16, 2016 at 2:02
  • thank you, adding that to my growing library. Commented Mar 16, 2016 at 9:25

2 Answers 2

1

Is this what you're looking for?

library(ggplot2)

males$nest <- as.factor(males$nest)
males$off <- as.factor(males$off)

ggplot(males, aes(x = nest, fill = off)) + 
geom_bar(width = 0.25) + 
scale_fill_manual(values = c('green', 'darkgreen'))

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Almost... I would like the two columns to be coloured according to if they have a nest or not e.g. 0 nest, green and light green, 1 nest, blue and light blue.
1

Done it! Thank you. It was the fill by interaction I was missing.

require(ggplot2)

males$off <- factor(as.numeric(males$off != 0))
males$nest <- as.factor(males$nest)

ggplot(males, aes(x = nest, fill = interaction(males$nest, males$off))) + geom_bar(width = 0.25) + scale_fill_manual(values = c('deepskyblue3', 'tomato3', 'deepskyblue', 'tomato'))

(Eventually needed the same number of lines of code as days googling...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.