smci
smci

Reputation: 33940

Stacked barplot is opposite order to legend?

A minor question about plotting stacked barplot in R. The stacked bars represent the series bottom-to-top. But the legend always shows the series top-to-bottom. I think that is also true with ggplot2::geom_bar

Is there any nicer idiom than using rev(...) twice inside either legend() or barplot() as in:

exports <- data.frame(100*rbind('Americas'=runif(6),'Asia'=runif(6),'Other'=runif(6)))
colnames(exports) <- 2004:2009
series_we_want <- c(1,2,3)
barplot( as.matrix(exports[series_we_want,]), col=mycolors, ...)
legend(x="topleft", legend=rev(rownames(exports)[series_we_want]), col=rev(mycolors) ...)

(If you omit one of the rev()'s the output is obviously meaningless. Seems like an enhance case for adding a single flag yflip=TRUE or yreverse=TRUE)

Upvotes: 0

Views: 1871

Answers (1)

Max C
Max C

Reputation: 2613

This is what I got using your code:

exports <- data.frame(100*rbind('Americas'=runif(6),'Asia'=runif(6),'Other'=runif(6)))
colnames(exports) <- 2004:2009
series_we_want <- c(1,2,3)
barplot( as.matrix(exports[series_we_want,]))
legend(x="topleft", legend=rev(rownames(exports)[series_we_want]))

enter image description here

try this:

exports <- data.frame(100*rbind('Americas'=runif(6),'Asia'=runif(6),'Other'=runif(6)))
colnames(exports) <- 2004:2009
series_we_want <- c(1,2,3)
test_data<-as.matrix(exports[series_we_want])

 barplot( test_data, 
          legend.text=as.character(rev(rownames(exports)[series_we_want])), 
           args.legend = list(x="topleft"))

seems to produce the legend in the opposite order of what you have

enter image description here

Upvotes: 1

Related Questions