Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: horizontal barplot with y-axis-labels next to every bar

Tags:

plot

r

label

axis

I want to design a barplot with 36 groups of 3 horizontal bars. Next to each group of 3, there should be one label.

My code is quite messed up (first time I use R), so I hope it will work with some dummy data...

Anyways:

Transcomp <- matrix(nrow=3, ncol=36)     # matrix
colnamesbarplot <- colnames(transComp)   # should be used as barplot labels
barplot <- 
barplot(transComp, 
    space=c(0,2),
    legend.text=TRUE,
    beside=TRUE,
    horiz=TRUE,
    density=NA,
    col=c("red1","red4","green3"),
    xlab="crimes per 100,000 inhabitants",
    ylab="districts and years",
    axes=TRUE
            )

I cannot find the paramenter that allows me to show a names of the columns directly next to the bars (I do not care whether they are on the left or on the right of the bars)... Could the problem maybe be the number of bars plotted?

The answeres in add text to horizontal barplot in R, y-axis at different scale? and labeling in barplot() and Axis labels for each bar and each group in bar charts with dodged groups don't get me where I wanna get...

Thank you for any help!

like image 766
PikkuKatja Avatar asked Jun 06 '13 12:06

PikkuKatja


1 Answers

Look at ?barplot arguments names.arg.

Some example data:

transComp <- matrix(sample(3*36), nrow=3, ncol=36)     
colnamesbarplot <- as.character(1:36)

The barplot:

barplot(transComp,space=c(0,2),legend.text=TRUE,beside=TRUE,horiz=TRUE,
    density=NA,
    col=c("red1","red4","green3"),
    xlab="crimes per 100,000 inhabitants",
    ylab="districts and years",
    axes=TRUE, names.arg=colnamesbarplot, cex.names=0.5, las=1)

Since you have many columns to plot you should set cex.names to make the labels smaller. The argument las=1 rotates the labels by 90 degrees.

like image 68
user1981275 Avatar answered Sep 28 '22 05:09

user1981275