之前有人在公眾號留言問文章開頭這幅圖如何實現(xiàn)鹤竭,下面的B圖是折線圖加柱形圖,相對比較容易實現(xiàn)拷呆,上面的A圖稍微有點復(fù)雜,我想到的辦法是拼圖疫粥,圖A可以看成三個熱圖茬斧,然后加一個堆積柱形圖,最后將四個圖組合到一起梗逮。那就按照這個思路試一下看能不能實現(xiàn)项秉。
最初的想法是左側(cè)的顏色條用堆積柱形圖來實現(xiàn),又看了一遍Y叔公眾號關(guān)于
aplot
這個包的推文慷彤,發(fā)現(xiàn)他是用geom_tile()
函數(shù)實現(xiàn)的娄蔼,仔細(xì)想想還是geom_tile()
函數(shù)實現(xiàn)起來比較方便。
首先解決昨天的遺留問題:ggplot2畫圖添加文字內(nèi)容的時候如何添加下劃線
非常感謝下面這位的留言
文本添加下劃線的小例子
df<-data.frame(A=1:10,
B=1:10)
library(ggplot2)
ggplot(df,aes(A,B))+
geom_point(size=5)+
theme_minimal()+
ggtitle(expression(underline("Good Good Study, Day Day Up")))+
labs(x=expression(paste(italic("ABC"),"123")))
下面進入今天推文的正式內(nèi)容
首先是準(zhǔn)備熱圖的數(shù)據(jù)
如何畫這個熱圖昨天的推文已經(jīng)介紹過了瞬欧,點擊下方藍(lán)色字可以直達昨天的推文
接下來是準(zhǔn)備分組顏色條的數(shù)據(jù)
下面是畫這個顏色條
df2<-read.csv("example_data/ggplot2_heatmap_color_bar.csv",header=T)
df2$y<-factor(df2$y,levels = rev(df2$y))
ggplot(df2,aes(x=x,y=y))+
geom_tile(aes(fill=group))+
scale_x_continuous(expand = c(0,0))+
theme(panel.background = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text.x = element_blank(),
legend.position = "left",
legend.title = element_blank())+
scale_fill_manual(values = c("green","blue","red"))
將分組顏色條和熱圖拼接到一起
library(aplot)
library(ggplot2)
df<-read.csv("example_data/ggplot2_heatmap.csv",header=T)
df1<-reshape2::melt(df)
df1$value1<-ifelse(is.na(df1$value),0,df1$value)
df1$value1<-as.factor(df1$value1)
df1$A<-factor(df1$A,levels = rev(df$A))
p1<-ggplot(df1,aes(x=variable,y=A))+
geom_tile(aes(fill=value1),color="black")+
scale_fill_manual(values = c("white","orangered","red2","red4"))+
scale_x_discrete(position = "top")+
theme(panel.background = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
axis.text.x.top = element_text(angle = 90,
hjust = 0,
vjust= 0.5),
plot.title = element_text(hjust=0.5),
legend.position = "none")+
labs(title = expression(underline("Plant growth and development")))+
geom_text(aes(label=value1,color=value1))+
scale_color_manual(values = c("white","black","black","black"))
df2<-read.csv("example_data/ggplot2_heatmap_color_bar.csv",header=T)
df2$y<-factor(df2$y,levels = rev(df2$y))
p2<-ggplot(df2,aes(x=x,y=y))+
geom_tile(aes(fill=group))+
scale_x_continuous(expand = c(0,0))+
theme(panel.background = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
legend.position = "left",
legend.title = element_blank())+
scale_fill_manual(values = c("green","blue","red"))
p1%>%
insert_left(p2,width = 0.05)
這里遇到一個問題是如何將右側(cè)的圖例放大左上角去贷屎?用代碼如何實現(xiàn)我暫時還不知道,出圖以后手動編輯吧艘虎!
接下來是模仿文章開頭,拼接三個熱圖
p3<-p1+
theme(axis.text.y = element_blank())
pdf(file = "123.pdf",width = 12)
p1%>%
insert_left(p2,width = 0.05)%>%
insert_right(p3)%>%
insert_right(p3)
dev.off()
這樣文章開頭提到的圖就做好了
歡迎大家關(guān)注我的公眾號
小明的數(shù)據(jù)分析筆記本