position legend of a stacked bar plot

后端 未结 4 898
余生分开走
余生分开走 2020-12-29 04:57

I am trying to create a stacked bar plot, but I cannot position the legend so that it does not overlap any of the bars. I have tried adjusting the margins, setting xl

相关标签:
4条回答
  • 2020-12-29 05:40

    How about this:

    library(RColorBrewer)
    
    barplot(
        y,
        xlim=c(0, ncol(y) + 3),
        col=brewer.pal(nrow(y), "Paired"),
        ylab="My Variables",
        legend.text=TRUE,
        args.legend=list(
          x=ncol(y) + 3,
          y=max(colSums(y)),
          bty = "n"
        )
    )
    

    0 讨论(0)
  • 2020-12-29 05:50

    You should add xpd=TRUE in par()

    par(mfrow=.., mar=...,xpd=TRUE)
    
    0 讨论(0)
  • 2020-12-29 05:51

    Just for fun, here it is in ggplot2, without overlapping legend.

    set.seed(1234)
    x <- replicate(8, round(10 * rexp(2000, 10)))
    y <- apply(x, 2, function(column) table(factor(column, levels = 0:9)))
    y <- as.data.frame(y)
    colnames(y) <- paste('A', seq(1,ncol(y),1), sep='')
    rownames(y) <- paste('R', seq(1,nrow(y),1), sep='')
    
    library(ggplot2)
    library(reshape)
    y$ID <- rownames(y)
    y.melt <- melt(y, id.var = 'ID')
    
    y.melt <- within(y.melt, ID <- factor(ID, 
        c('R10','R9','R8','R7','R6','R5','R4','R3','R2','R1'), 
        ordered = TRUE))
    
    ggplot(y.melt, aes(x = variable, y = value, fill = ID)) +
        geom_bar(stat = 'identity') +
        xlab("") +
        ylab("My variable") +
        theme(legend.title=element_blank())
    

    bar chart

    0 讨论(0)
  • 2020-12-29 05:52

    With margins

    par(mfrow=c(1, 1), mar=c(5, 5, 4, 8))
    barplot(y, col = 1:nrow(y), ylab="My Variables", legend.text = TRUE, 
            args.legend = list(x = "topright", bty = "n", inset=c(-0.15, 0)))
    
    0 讨论(0)
提交回复
热议问题