position legend of a stacked bar plot

后端 未结 4 906
余生分开走
余生分开走 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: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

提交回复
热议问题