data<-melt(mydata,id.vars = 'ID') p <- ggplot(data=data,aes(ID,value,fill=variable)) + geom_bar(stat="identity",position="stack", color="#f0f0f0", width=1,size=0.20) + scale_fill_manual(values=c("#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99", "#e31a1c","#fdbf6f","#ff7f00","#cab2d6", "#6a3d9a","#ffff99","#ffed6f","#ccebc5", "#bc80bd","#d9d9d9","#fccde5","#b3de69", "#fdb462","#80b1d3","#fb8072","#8dd3c7", "#fdb222","#92b1d0","#fb8098","#9dd3c7")) p+labs(x = "", y = "") + #scale_x_continuous(breaks = seq(min(data$ID), max(data$ID), by = 1)) + # Add this line scale_y_continuous(expand = c(0,0),limits = c(0,100),breaks = seq(0, 100, by = 20)) + theme_classic() + theme( panel.background = element_rect(fill="white", colour="white", size=0.25), axis.line = element_line(colour="black", size=0.5), axis.title = element_text(size=13, color="black"), axis.text = element_text(size=12, color="black"), legend.position = c(1.15, 0.5), #修改图例位置 legend.text = element_text(size =10), aspect.ratio = 1, # set figure size to 8x6 inches plot.title = element_text(size = 10), # optional, add a title axis.text.x = element_text(angle = 45, hjust = 1), # Rotate x-axis labels by 45 degrees legend.box.spacing = unit(0.01, "cm"), # 设置图例中每个元素的间距 #legend.key.width = 0.5, # 缩小图例颜色方块的宽度 legend.background = element_blank() # 设置图例背景为透明 ) + guides(fill = guide_legend(ncol = 1,title="Bac_Phylum")) 修改脚本,图片中顺序与数据顺序一致