ggplot2 修改图例的一些操作

时间:2022-07-22
本文章向大家介绍ggplot2 修改图例的一些操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先做一幅简单的散点图,使用的数据集是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")

image.png

不想要图例的标题可以直接加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)))