R语言 如何把有多行的ggplot2图例移到图的底部

R语言 如何把有多行的ggplot2图例移到图的底部

在这篇文章中,我们将看到如何在R编程语言中在底部绘制ggplot2图例,并且有两行。首先,我们必须创建一个带有图例的简单数据图。这里我们将绘制一个简单的散点图。

加载库

首先,通过使用 library() 函数加载ggplot2包。

 library("ggplot2")

以创建一个数据框架为例。在这里,我们创建了一个简单的DataFrame,其中有三个变量,分别是 Year , Points , 和 Users ,然后把它分配给数据对象。

library("ggplot2")
  
# Create a DataFrame
data <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015),
                   Points = c(30, 20, 15, 35, 50),
                   Users = c("user1", "user2", "user3",
                             "user4", "user5"))
print(data)

输出

如何在R语言中把有多行的ggplot2图例移到图的底部

数据帧

为了创建一个R图,我们使用 ggplot() 函数,为了使它成为散点图,我们将 geom_point() 函数添加到 ggplot ()函数中。

代码

# Load Package
library("ggplot2")
  
# Create a DataFrame 
data <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015),
                   Points = c(30, 20, 15, 35, 50),
                   Users = c("user1", "user2", "user3", 
                             "user4", "user5"))
  
# Create a Scatter Plot and assign it 
# to gplot data object
gplot <- ggplot(data, aes(Year, Points, color = Users)) +   
  geom_point(size = 7)
gplot

输出

如何在R语言中把有多行的ggplot2图例移到图的底部

带图例的简单散点图

在图的底部绘制ggplot2图例

为了在图的底部绘制ggplot2图例,我们只需在geom_point()函数中添加theme()函数。

语法: theme(legend.position)

参数: 一般来说,theme()函数有很多参数来指定绘图的主题,但这里我们只使用 legend.position 参数来指定图例的位置。

返回: 绘图的主题。

我们可以指定 legend.position 参数的值,包括 顶和底。 要在图的底部绘制图例,我们使用’bottom’作为 legend.position 参数的值。

# Load Package
library(ggplot2)
  
# Create a DataFrame For plot
data <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015),
                   Points = c(30, 20, 15, 35, 50),
                   Users = c("user1", "user2", "user3", 
                             "user4", "user5"))
  
# Create a simple scatter plot 
# with legend at bottom.
ggplot(data, aes(Year, Points, color = Users)) +   
  geom_point(size = 7)+
  theme(legend.position = "bottom")

输出

如何在R语言中把有多行的ggplot2图例移到图的底部

散点图,底部有图例

在底部用两行绘制ggplot2图例

如果我们想在图的底部绘制两行的ggplot2图例,我们必须在theme()函数中添加guide和guide_legend函数。在guards()函数中,我们取名为 color 的参数,该参数以调用guide_legend()引导函数为值。在guide_legend()函数中,我们接受一个名为 nrow 的参数,该参数的值是所需的图例行数。

语法 : guide_legend(nrow)

参数 :

  • nrow: 期望的图例行数。

返回: 各种比例的图例指南

代码

# Load Package
library(ggplot2)
  
# Create a DataFrame For plot
data <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015),
                   Points = c(30, 20, 15, 35, 50),
                   Users = c("user1", "user2", "user3",
                             "user4", "user5"))
  
# Create a simple scatter plot with
# legend at bottom and with Two Rows.
# Specifies the Number of legend Rows
ggplot(data, aes(Year, Points, color = Users)) +   
  geom_point(size = 7)+
  theme(legend.position = "bottom")+
  guides(color = guide_legend(nrow = 2))      

输出

如何在R语言中把有多行的ggplot2图例移到图的底部

散点图,底部有两行的图例

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程