首先做一幅简单的散点图,使用的数据集是R语言里自带的iris
library(ggplot2)
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=Species),size=5)

下面对图例进行操作
首先是更改图例的标题
现在上面的图图例的标题是Species,我现在想把他改为cultivar
第一种方法是直接在原数据集上改,因为这个图例的标题对应的是数据的列名,我把列名改了就可以了
iris1<-iris
colnames(iris1)<-c(colnames(iris)[1:4],'cultivar')
colnames(iris1)
ggplot(iris1,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=cultivar),size=5)

第二种方法是使用guides()
函数
参考https://stackoverflow.com/questions/14622421/how-to-change-legend-title-in-ggplot
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=Species),size=5)+
guides(color=guide_legend(title = "ABC"))
这样就直接把图例的标题改为了ABC

第三种方法直接使用labs()
函数来修改
ggplot(iris1,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=cultivar),size=5)+
labs(color="ABCDE")

不想要图例的标题可以直接加theme(legend.title="none")
接下来是更改图例的大小
如果更改点的大小,右侧图例的大小也会跟着改变
比如
ggplot(iris1,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=cultivar),size=15)

这个时候我想要让右侧图例的小一点
参考
https://stackoverflow.com/questions/15059093/ggplot2-adjust-the-symbol-size-in-legends
ggplot(iris1,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=cultivar),size=15)+
guides(color=guide_legend(override.aes = list(size=2)))

接下来是更改三个图例的文字标签
比如我想把 三个品种名分别改成A,B,C
第一种方法还是直接改数据
第二种方法使用factor()
函数,原来这个函数还有一个label参数
参考
http://t-redactyl.io/blog/2016/01/creating-plots-in-r-using-ggplot2-part-4-stacked-bar-plots.html
iris1$cultivar<-factor(iris1$cultivar,
levels = c('setosa','versicolor','virginica'),
labels = c("A","B","C"))
ggplot(iris1,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=cultivar),size=15)+
guides(color=guide_legend(override.aes = list(size=2)))

以上就是今天介绍的一些关于ggplot2修改图例的一些操作,欢迎大家在我的公众号留言
小明的数据分析笔记本

网友评论