将堆叠条形图的部分拆分为单独的系列

Split parts of a stacked barplot into individual series

我想在 R 3.2.2 中创建一个带有堆叠条的条形图,但每个条的每个部分都分成一个单独的系列。

示例数据框:

num_var_x = 14
num_var_y = 17

x = runif(num_var_x, 0.0, 1.0)
norm = x/sum(x)
data = data.frame(replicate(num_var_y,sample(norm)))

编辑:

感谢 Floo0,我想出了这个代码的延续:

## preparing dataset for ggplot

require(ggplot2)
require(reshape2)
data$no <- seq_len(nrow(data))
data_molten <- melt(data, id.vars = "no")

data_molten_sort = data_molten[with(data_molten,order(no)),]

## removing elements from variable 'no' whose max. value is e.g. < 0.025

sequence = seq(from=1, to=(num_var_y*num_var_x-num_var_x)+1, by=num_var_x)
for(i in 1:length(sequence))
{
    if(isTRUE((max(data_molten_sort$value[(sequence[i]):((num_var_x+sequence[i])-(1))])) < 0.025))
    {
            data_molten_sort$value[(sequence[i]):((num_var_x+sequence[i])-(1))] = NA
    }
}

View(data_molten)


## preparing posterior exporting

#install.packages("Cairo"); "cairo" type in png() has a better quality
library("Cairo")
#preparing exporting
png(file="ggplot.png",type="cairo", width = 4, height = 5, units = 'in',pointsize=8,res=600)

## plotting

ggplot(data_molten[!is.na(data_molten$value),], aes(x = variable, y = value, fill = factor(no))) + 
    geom_bar(stat = "identity") + 
    scale_fill_hue(l=40) + facet_grid(no~., as.table=FALSE, scale="free_y", space = "free_y") + theme_minimal() +
    geom_vline(xintercept=max(as.numeric(data_molten$variable)) + 0.586, size=0.3) +
    theme(legend.position="none", 
          axis.text.x = element_text(angle = 90, colour="black", vjust = 0.4, hjust=1, size=8), 
          axis.title.x = element_blank(), axis.title.y = element_blank(), 
          axis.line.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(), 
          strip.text.y=element_text(size = 8, colour="black", family="", angle=00,hjust = 0.1),
          panel.grid=element_blank(),
          axis.line=element_line(size = 0.3, colour = "black", linetype = "solid"),
          axis.ticks.x=element_line(size = 0.3, colour = "black", linetype = "solid"),
          panel.background=element_blank(), panel.margin = unit(0, "lines"))

## exporting barplot "ggplot.png" to directory
dev.off()

生成所需的条形图:

http://i.imgur.com/C6h5fPg.png?1

您可以使用 ggplot2 执行以下操作:

require(ggplot2)
require(reshape2)
data$no <- seq_len(nrow(data))
data_molten <- melt(data, id.vars = "no")

如果您希望行具有不同的高度,请查看:

我不是 100% 确定你希望情节转向哪个方向:

版本 1

ggplot(data_molten, aes(x = no, y = value, fill = variable)) + geom_bar(stat = "identity") +
  facet_grid(variable~.) + theme(legend.position="none")

版本 2
感谢评论

ggplot(data_molten, aes(x = variable, y = value, fill = factor(no))) + geom_bar(stat = "identity") +
  facet_grid(no~.) + theme(legend.position="none")

原创

ggplot(data_molten, aes(x = no, y = value, fill = variable)) + geom_bar(stat = "identity")