之前的推文 跟著Nature microbiology學(xué)畫圖~R語言ggplot2畫氣泡圖 有人問到如何將圖例的 實心點 改為 空心點 ,當(dāng)時我自己也不知道,第二天他自己搞定了,并且把實現(xiàn)代碼發(fā)給了我,在這里記錄一下如何實現(xiàn)
常規(guī)氣泡圖的圖例
示例數(shù)據(jù)就直接用內(nèi)置的鳶尾花的數(shù)據(jù)集了
library(ggplot2)
colnames(iris)
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(size=Petal.Length,color=Species))+
guides(color=F)+
scale_size_continuous(range = c(5,10),
breaks = c(2,4,6))

image.png

image.png
那如何變成如上這種空心的圓呢?
我開始想復(fù)雜了,以為需要去圖例相關(guān)的參數(shù)里進行設(shè)置,原來直接更改點的形狀就好了,給shape參數(shù)設(shè)置成21就好了
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(size=Petal.Length,color=Species),
shape=21)+
guides(color=F)+
scale_size_continuous(range = c(5,10),
breaks = c(2,4,6))

image.png
這樣的話圖上的點也都變成空心的了,如果想把圖上的點設(shè)置成實心的,就再增加一個fill參數(shù)就好了
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(size=Petal.Length,
color=Species,
fill=Species),
shape=21)+
guides(color=F,fill=F)+
scale_size_continuous(range = c(5,10),
breaks = c(2,4,6))

image.png
這里還可以看到圖例是帶灰色背景的,如果想要去掉怎么辦呢?答案是在主題里設(shè)置
legend.key參數(shù)
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(size=Petal.Length,
color=Species,
fill=Species),
shape=21)+
guides(color=F,fill=F)+
scale_size_continuous(range = c(5,10),
breaks = c(2,4,6))+
theme(legend.key = element_blank())

image.png
這里的key對應(yīng)的中文意思是什么呢?

image.png
添加橢圓的分組邊界
用到的是stat_ellipse()函數(shù)
ggplot(data=iris,aes(x=Sepal.Length,
y=Sepal.Width,
color=Species))+
geom_point()+
theme(legend.key = element_blank())+
stat_ellipse(aes(x=Sepal.Length,
y=Sepal.Width,
color=Species,
fill=Species),
geom = "polygon",
alpha=0.5)

image.png
添加圓形的分組邊界
用到的是ggforce這個包里的geom_circle()函數(shù)
library(ggplot2)
library(ggforce)
colnames(iris)
ggplot()+
geom_point(data=iris,aes(x=Sepal.Length,
y=Sepal.Width,
color=Species))+
theme(legend.key = element_blank(),
panel.background = element_blank(),
panel.border = element_rect(color="black",
fill = "transparent"))+
geom_circle(aes(x0=5,y0=3.5,r=1),
fill="blue",
alpha=0.2,
color="red")+
xlim(2,8)+
ylim(2,8)+
geom_circle(aes(x0=7,y0=3,r=1),
fill="green",
alpha=0.2,
color="red")

image.png
歡迎大家關(guān)注我的公眾號
小明的數(shù)據(jù)分析筆記本