Reputation: 21
I am attempting to add names to the columns of my bar plot... There are 2 bars in each group that would share the same name..
I am using code like this:
l<-c(.6286, .2212, .9961, .5831, .8703, .6990, .9952, .9948)
r<-c(.2721, .5663, .0, .3961, .0696, .1180, .0, .0)
tab<-rbind(l,r)
plot<-barplot(tab, beside=TRUE, axisnames=FALSE, main = 'Time Spent Left vs. Right', sub = 'Female 2c', xlab= 'Days After Entry', ylab = 'Proportion of Time Spent', col=c('blue', 'red'), ylim = c(0,1))
legend('topleft', .8, c('Left' , 'Right'), pch=c(.8), col=c('blue', 'red'))
names.arg = jd2c$d.in.p
names.arg=c(3,4,5,6,6,7,10,11) #listed for informational purposes, same as jd2c$d.in.p
jd2c$d.in.p is also listed above.. For some reason the names.arg function does not seem to be doing what I would expect. Even if I put it within the parenthesis of the bar plot() function..
What am I doing wrong?
Thank you!
Upvotes: 2
Views: 6046
Reputation: 78630
You are defining names.arg
not as an argument to the barplot
function, but as a completely separate variable- it is outside the parentheses. This:
plot<-barplot(tab, beside=TRUE, axisnames=FALSE, main = 'Time Spent Left vs. Right', sub = 'Female 2c', xlab= 'Days After Entry', ylab = 'Proportion of Time Spent', col=c('blue', 'red'), ylim = c(0,1))
legend('topleft', .8, c('Left' , 'Right'), pch=c(.8), col=c('blue', 'red'))
names.arg = jd2c$d.in.p
should be:
plot<-barplot(tab, beside=TRUE, axisnames=FALSE, main = 'Time Spent Left vs. Right', sub = 'Female 2c', xlab= 'Days After Entry', ylab = 'Proportion of Time Spent', col=c('blue', 'red'), ylim = c(0,1), names.arg = jd2c$d.in.p)
legend('topleft', .8, c('Left' , 'Right'), pch=c(.8), col=c('blue', 'red'))
You must also set axisnames=TRUE
for the names to appear.
Upvotes: 1
Reputation: 226871
Using your data and setting names.arg
appropriately and axisnames=TRUE
, I get a reasonable result. I tweaked a couple of other things (set las=1
to turn axis labels horizontal, used fill
rather than col
in the legend, got rid of pch=0.8
).
par(las=1)
bnames <- c(3,4,5,6,6,7,10,11) #listed for informational purposes, same as jd2c$
plot<-barplot(tab, beside=TRUE, axisnames=TRUE,
main = 'Time Spent Left vs. Right',
sub = 'Female 2c', xlab= 'Days After Entry',
ylab = 'Proportion of Time Spent',
col=c('blue', 'red'), ylim = c(0,1),
names.arg=bnames)
legend('topleft', cex=1, c('Left' , 'Right'), fill=c('blue', 'red'))
Upvotes: 1