Ggplot2 简明教程

ggplot2 - Working with Legends

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

Axes and legends are collectively called as guides. They allow us to read observations from the plot and map them back with respect to original values. The legend keys and tick labels are both determined by the scale breaks. Legends and axes are produced automatically based on the respective scales and geoms which are needed for plot.

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

Following steps will be implemented to understand the working of legends in ggplot2 −

Inclusion of package and dataset in workspace

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

Let us create the same plot for focusing on the legend of the graph generated with 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

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

If you observe the plot, the legends are created on left most corners as mentioned below −

legends are created

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

Here, the legend includes various types of species of the given dataset.

Changing attributes for legends

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

We can remove the legend with the help of property “legend.position” and we get the appropriate output −

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

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

We can also hide the title of legend with property “element_blank()” as given below −

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

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

We can also use the legend position as and when needed. This property is used for generating the accurate plot representation.

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

Top representation

Top representation

top representation

Bottom representation

Bottom representation

bottom representation

Changing font style of legends

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

We can change the font style and font type of title and other attributes of legend as mentioned below −

> #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"))

下面给出了生成的输出 −

The output generated is given below −

changing font style of legends
changing font style of legends1

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

Upcoming chapters will focus on various types of plots with various background properties like color, themes and the importance of each one of them from data science point of view.