Ggplot2 简明教程

ggplot2 - Working with Legends

坐标轴和图例统称为指南。它们允许我们从绘图中读取观察结果,并将它们映射回原始值。图例键和刻度标签都由刻度断点确定。图例和坐标轴根据绘图所需的相应刻度和几何自动生成。

将执行以下步骤来了解 ggplot2 中图例的工作原理 −

Inclusion of package and dataset in workspace

让我们创建相同的绘图来关注使用 ggplot2 生成的图表的图例 −

> # Load ggplot
> library(ggplot2)
>
> # Read in dataset
> data(iris)
>
> # Plot
> p <- ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) + geom_point()
> p
inclusion of package and dataset

如果你观察该绘图,图例创建在最左角,如下所示 −

legends are created

在此,图例包括给定数据集的各种物种类型。

Changing attributes for legends

我们可以借助属性 “legend.position” 来移除图例,并且可以获得适当的输出 −

> # Remove Legend
> p + theme(legend.position="none")
changing attributes for legends

我们还可以使用属性 “element_blank()” 隐藏图例的标题,如下所示 −

> # Hide the legend title
> p + theme(legend.title=element_blank())
element blank

我们还可以根据需要使用图例位置。此属性用于生成准确的绘图图例。

> #Change the legend position
> p + theme(legend.position="top")
>
> p + theme(legend.position="bottom")

Top representation

top representation

Bottom representation

bottom representation

Changing font style of legends

我们可以更改标题的字体样式和字体类型以及图例的其他属性,如下所示 −

> #Change the legend title and text font styles
> # legend title
> p + theme(legend.title = element_text(colour = "blue", size = 10, + face = "bold"))
> # legend labels
> p + theme(legend.text = element_text(colour = "red", size = 8, + face = "bold"))

下面给出了生成的输出 −

changing font style of legends
changing font style of legends1

后续章节将重点介绍不同类型的绘图以及各种背景属性,例如颜色、主题以及每种属性对于数据科学的意义。