[R] Different stack barplots - same color legends

David L Carlson dc@r|@on @end|ng |rom t@mu@edu
Mon Oct 22 17:13:40 CEST 2018

Your example is not reproducible since you did not give us some sample data. I suspect that your data frame consists of columns that represent questions and rows that represent individuals who answered the questions. First create a simple example:

teamq <- data.frame(V1=sample(c(1, 2, 4, 5), 25, replace = TRUE),
     V2=sample(c(1, 2, 3, 4, 5), 25, replace=TRUE), 
     V3=sample(c(2, 3, 4, 5), 25, replace=TRUE))

Notice that this data frame ONLY contains questions (and only 3 questions). Here are 2 ways to get what you want. The first one stacks the data:

teamq.stack <- stack(teamq)
counts <- table(teamq.stack)

The second one converts each column to a factor with levels 1 - 5:

teamq2 <- data.frame(lapply(teamq, factor, levels=1:5))
counts <- sapply(teamq2, table)

Now make the plots:

cols <- c("yellow","sandybrown","orange", "darkolivegreen","green")
barplot(counts[, 1], horiz=TRUE, col=cols, legend=TRUE)
barplot(counts[, 2], horiz=TRUE, col=cols, legend=TRUE)
barplot(counts[, 3], horiz=TRUE, col=cols, legend=TRUE)

You will need to adjust the xlim= argument so that the legend does not print on top of the bars.

David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77843-4352

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of P. Roberto Bakker
Sent: Monday, October 22, 2018 9:04 AM
To: R mailing list <r-help using r-project.org>
Subject: [R] Different stack barplots - same color legends


I want to make barplots from different questions (columns) in one
Each question has the same 5 likert items.
Now the problem: in some questions all items are answered; in other less.
>From the syntax below I get nice stack barplots - *but the legend colors do
not* refer to the same likert-item, which I understand - the colors go in
sequence along the table.
Question: how can I write a syntax that each likert-item has the same
legend color?
Thank you in advance,


counts19 <- table(teamq[,19])
counts20 <- table(teamq[,20])
barplot(as.matrix(counts19), horiz = T,
        col=c("yellow","sandybrown","orange", "darkolivegreen","green"),
barplot(as.matrix(counts20), horiz = T,
        col=c("yellow","sandybrown","orange", "darkolivegreen","green"),

	[[alternative HTML version deleted]]

R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list