安裝乔询、加載包
#設(shè)置工作環(huán)境
rm(list=ls())
setwd("D:\\桌面\\ggplot2添加圖例及圖例相關(guān)設(shè)置")
#加載包
# install.packages("ggpubr")
# install.packages('ggplot2')
# install.packages('reshape2')
#加載包
library(ggpubr)
library(ggplot2)
library(reshape2)
加載數(shù)據(jù)并繪圖
#讀取數(shù)據(jù)
df <- read.table(file="Genus.txt",sep="\t",header=T,check.names=FALSE,row.names = 1)
#轉(zhuǎn)換數(shù)據(jù)
df$Tax=rownames(df)
df1=melt(df)
colnames(df1)=c("Tax","Samples","value")
#繪圖
p <- ggplot(df1, aes(x = Samples, y = Tax, size = value, color=Samples)) +
geom_point(aes(size=value))+
theme(panel.background = element_blank(),
panel.grid.major = element_line(color = "gray"),#網(wǎng)格線條顏色
panel.border = element_rect(color="black",fill=NA))#邊框色
p
image.png
圖例設(shè)置
1太雨、圖例關(guān)閉——三種方法
p+theme(legend.position = 'none')#關(guān)閉全部圖例
image.png
p+guides(color='none')#關(guān)閉部分圖例督弓,如圖例中散點(diǎn)顏色的部分圖例
p+scale_color_discrete(guide='none')#關(guān)閉部分圖例芦圾,如圖例中散點(diǎn)顏色的部分圖例
image.png
2、圖例位置帝牡,可以通過(guò)theme中的legend.position函數(shù)控制圖例位置
p+theme(legend.position = 'top')#控制圖例放置在圖中上下左右('top','bottom','right','left')
image.png
p+theme(legend.position = c(0.95,0.6))#通過(guò)設(shè)置位置坐標(biāo)控制圖例位置往毡,范圍為0~1
image.png
3、圖例方向——通過(guò)legend.direction函數(shù)或者guides中的guide_legend控制:
p+theme(legend.direction = 'horizontal')#有垂直與豎直兩種方向靶溜,‘horizontal’开瞭,‘vertical’
image.png
#精準(zhǔn)設(shè)置
p+guides(color=guide_legend(ncol = 3,#根據(jù)ncol或者nrow設(shè)置圖例顯示行數(shù)或列數(shù)(設(shè)置一個(gè)即可)
byrow = T,#默認(rèn)F,表示按照列填充
reverse = T))#默認(rèn)F罩息,表示升序填充嗤详,反之則降序
image.png
4、圖例標(biāo)題去除——三種方式
p+theme(legend.title = element_blank())#刪除所有圖例
image.png
p+labs(color=NULL)#刪除所有圖例
p+scale_color_discrete(name=NULL)#只刪除部分圖例
image.png
5瓷炮、圖例符號(hào)周?chē)鷧^(qū)域大小及符號(hào)本身大小設(shè)置
p+theme(legend.key.size = unit(20,"point"))#增加符號(hào)周?chē)膮^(qū)域
image.png
p+guides(color = guide_legend(override.aes = list(size = 5)))#改變符號(hào)大小
image.png
6葱色、圖例框的填充顏色
p+theme(legend.key = element_rect(fill = 'green'))
image.png
7、自定義圖例標(biāo)簽順序——通過(guò)將數(shù)據(jù)中的相應(yīng)列數(shù)據(jù)轉(zhuǎn)換為factor型數(shù)據(jù)進(jìn)而調(diào)整顯示順序
df1$Samples=factor(df1$Samples,levels = c('B','A','D','C','F','G','H','I','J','E','K'))#定義順序
ggplot(df1, aes(x = Samples, y = Tax, size = value, color=Samples)) +
geom_point(aes(size=value))+
theme(panel.background = element_blank(),
panel.grid.major = element_line(color = "gray"),#網(wǎng)格線條顏色
panel.border = element_rect(color="black",fill=NA))#邊框色
image.png