干货分享 | 小小代码造就精美绘图——“瀑布图”
发布时间 2022-08-05
绘图用R包
包含大量专业绘图色,绘制多样本图的基础
用于整理数据的R包
library(ggplot2) library(RColorBrewer) library(reshape2)
文件命名为Waterfall_Data.csv
data<-read.csv("Waterfall_data.csv",stringsAsFactors=FALSE)
colnames(data)<-c("X_Axis",seq(60,25,-5)) plotdata<-melt(data,id.vars = "X_Axis")
ggplot(plotdata,aes(X_Axis,value,fill=variable))+
geom_area(color="black",size=0.25)+
facet_grid(variable~.)+
theme(
text=element_text(size=15,face="plain",color="black"),
axis.title=element_text(size=10,face="plain",color="black"),
axis.text = element_text(size=10,face="plain",color="black"),
legend.position="none"
)
相对于行分面瀑布图,3D瀑布图中不同类别间的差异更为直观,能更好地观察类与类之间的差距。
library(plot3D) library(RColorBrewer)
data<-read.csv("Facting_Data.csv",check.names =FALSE)
N<-ncol(data)-1 plotdata<-data.frame(x=numeric(),y=numeric(),variable=character()) for (i in 1:N){ tempdata<-data.frame(spline(data[,1],data[,i+1],n=300,method= "natural")) tempdata$variable<-colnames(data)[i+1] plotdata<-rbind(plotdata,tempdata) }#插值处理 plotdata$variable<-as.numeric(plotdata$variable) group<-unique(plotdata$variable) M<-length(group)
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
colormap <- rev(gg_color_hue(M))#brewer.pal(M,'RdYlGn')
pmar <- par(mar = c(5.1, 4.1, 4.1, 6.1))
perspbox(z=as.vector(0),#add=TRUE,xlim=c(20,70),ylim=c(360,750),zlim=c(0,15),
ticktype = "detailed",bty = "f",box = TRUE,colkey = FALSE,
theta = -110, phi = 20, d=3)
for (i in 1:M){
df0<-plotdata[plotdata$variable==group[i],]
Ndf<-nrow(df0)
df<-rbind(df0,c(df0$x[1],df0$y[Ndf],df0$variable[Ndf]))
with(df,polygon3D(x=variable,y=x, z=y, alpha=0.6,
col=colormap[i],lwd = 3,add=TRUE,colkey = FALSE))
with(df0,lines3D(x=variable,y=x, z=y,
lwd = 0.5,col="black",add=TRUE))
}
colkey (col=colormap,clim=range(plotdata$y),clab = "Z Value", add=TRUE, length=0.5,side = 4)#
备注:X轴变量数据(不同样本)、不同的Y轴离散型变量(不同指标)、Z轴数值变量(指标相对含量)