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

23,046

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.

Share:
23,046
PikkuKatja
Author by

PikkuKatja

student of economics and manangement, not much experience with statistics and programming yet. Glad to be able to get advise from these wonderful people on stackoverflow!

Updated on July 28, 2022

Comments

  • PikkuKatja
    PikkuKatja almost 2 years

    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!

  • PikkuKatja
    PikkuKatja almost 11 years
    yes! So the las was what I was missing to make it work! Stackoverflow, you are wonderful!