設(shè)置工作目錄、加載R包
rm(list = ls())
#設(shè)置工作目錄
setwd("D:\\圖片顏色提取")
#加載R包
library(RImagePalette)
library(imager)
library(scales)
library(ggplot2)
library(ggprism)
library(reshape)
library(ggalluvial)
加載圖片并提取顏色
1瞳购、圖片加載及預(yù)覽——jpg格式圖片加載主要基于imager包中的load.image()函數(shù):
##圖1
imgjpg1 <- load.image("test1.jpg")#讀取圖片
plot(imgjpg1,xlim = c(1,width(imgjpg1)),ylim = c(height(imgjpg1),1)) #顯示圖片
2、提取圖片顏色——主要基于RImagePalette包中的image_palette()函數(shù):
#提取圖片顏色
df_color1 <- image_palette(imgjpg1,n=10)
show_col(df_color1)#展示
3刑峡、同樣的原理提取其他圖片顏色:
##圖2
imgjpg2 <- load.image("test2.jpg")#讀取圖片
plot(imgjpg2,xlim = c(1,width(imgjpg2)),ylim = c(height(imgjpg2),1)) #顯示圖片
#提取圖片顏色
df_color2 <- image_palette(imgjpg2,n=10)
show_col(df_color2)
##圖3
imgjpg3 <- load.image("test3.jpg")#讀取圖片
plot(imgjpg3,xlim = c(1,width(imgjpg3)),ylim = c(height(imgjpg3),1)) #顯示圖片
#提取圖片顏色
df_color3 <- image_palette(imgjpg3,n=10)
show_col(df_color3)
##圖4
imgjpg4 <- load.image("test4.jpg")#讀取圖片
plot(imgjpg4,xlim = c(1,width(imgjpg4)),ylim = c(height(imgjpg4),1)) #顯示圖片
#提取圖片顏色
df_color4 <- image_palette(imgjpg4,n=10)
show_col(df_color4)
應(yīng)用提取圖片的顏色繪圖
1吻氧、構(gòu)造繪圖數(shù)據(jù)
df<-data.frame(samples=c('a','b','c','d','e','f','g','h','i','j'),
A=c(0.12,0.15,0.1,0.07,0.1,0.1,0.08,0.1,0.13,0.05),
B=c(0.35,0.1,0.05,0.05,0.05,0.1,0.1,0.05,0.1,0.05),
C=c(0.25,0.15,0.1,0.07,0.1,0.1,0.05,0.05,0.08,0.05),
D=c(0.05,0.2,0.1,0.2,0.1,0.1,0.1,0.05,0.05,0.05))
#變量格式轉(zhuǎn)換,寬數(shù)據(jù)轉(zhuǎn)化為長數(shù)據(jù),方便后續(xù)作圖
df1 <- melt(df,id.vars = 'samples',measure.vars = c('A','B','C','D'))
names(df1)[1:2] <- c("group","X") #修改列名
2、繪圖
#繪圖
p<-ggplot(df1, aes( x = X,y=100 * value,fill = group,
stratum = group, alluvium = group))+
geom_stratum(width = 0.7, color='white')+
geom_alluvium(alpha = 0.5,
width = 0.7,
color='white',
size = 1,
curve_type = "linear")+
scale_y_continuous(expand = c(0,0))+
labs(x="Samples",y="Relative Abundance(%)",
fill="group")+
theme_prism(palette = "candy_bright",
base_fontface = "plain",
base_family = "serif",
base_size = 16,
base_line_size = 0.8,
axis_text_angle = 45)+
theme(legend.position = 'top')
p
3融欧、應(yīng)用繪圖顏色并拼圖
#應(yīng)用顏色
p2<-p+scale_fill_manual(values = df_color1)
p3<-p+scale_fill_manual(values = df_color2)
p4<-p+scale_fill_manual(values = df_color3)
p5<-p+scale_fill_manual(values = df_color4)
#拼圖
cowplot::plot_grid(p2,p3,p4,p5,ncol = 2)