Brooke
Brooke

Reputation: 49

How can I make a bar chart where I can sub-divide each of the three x-axis categories?

I'm attempting to make a bar graph, using three different columns from my data set to make up the x-axis (Number_DS, Number_US, Number_A), (and 'Number attracted' as the y-axis) with each of these three variables representing data for each of three different fish species, so basically, three categories on the axis, each subdivided into three sub-categories.

The graph below (which I made by summarising data I had on a previous occasion and producing a concise matrix) shows the kind of graph I'm attempting to produce (without the error bars).

In addition, I'm also planning on calculating standard error or deviation to produce error bars for each. However, I'm struggling to find a way to do so with my data in the format that it is in (different to previous occasion). Does anyone have any code that may help sort the data in a way that generating this graph is possible? I've added some of my data below in hopes that it helps this question make more sense!

Thank in advance

enter image description here

Species         NumberDS    NumberUS    NumberAcross   Number attracted
Atlantic cod    0            0           92             0
Atlantic cod    0            2           0              0
Haddock         9            0           0              9
Whiting         0            0           4              4
Haddock         0            0           1              0
Whiting         0            1           2              3

Upvotes: 1

Views: 310

Answers (1)

Robert
Robert

Reputation: 5152

I don't know if I got your problem. Assuming df is your data.frame.

sps=split(df,df$Species) #Species is the first column
totals=sapply(sps,function(sp)apply(sp[,-1],2,sum))

bp=barplot(as.matrix(t(totals)),legend.text = TRUE,args.legend=
          list(x = "topright",bty="n",cex=.8,ncol=1),
        beside=T,col=1:ncol(totals),xaxt="n")
axis(1,at=bp[2,],labels=row.names(totals),las=2,cex.axis=.5,tick = F)

Is that what you want?

enter image description here

Upvotes: 1

Related Questions