设置工作目录、加载R包
rm(list = ls())
#设置工作目录
setwd("D:\\图片颜色提取")
#加载R包
library(RImagePalette)
library(imager)
library(scales)
library(ggplot2)
library(ggprism)
library(reshape)
library(ggalluvial)
加载图片并提取颜色
1、图片加载及预览——jpg格式图片加载主要基于imager包中的load.image()函数:
##图1
imgjpg1 <- load.image("test1.jpg")#读取图片
plot(imgjpg1,xlim = c(1,width(imgjpg1)),ylim = c(height(imgjpg1),1)) #显示图片
image.png
2、提取图片颜色——主要基于RImagePalette包中的image_palette()函数:
#提取图片颜色
df_color1 <- image_palette(imgjpg1,n=10)
show_col(df_color1)#展示
image.png
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)
image.png
image.png
##图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)
image.png
image.png
##图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)
image.png
image.png
应用提取图片的颜色绘图
1、构造绘图数据
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))
#变量格式转换,宽数据转化为长数据,方便后续作图
df1 <- melt(df,id.vars = 'samples',measure.vars = c('A','B','C','D'))
names(df1)[1:2] <- c("group","X") #修改列名
image.png
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
image.png
3、应用绘图颜色并拼图
#应用颜色
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)
image.png
网友评论