R语言 牛图网格的共享图例

R语言 牛图网格的共享图例

在这篇文章中,我们将讨论如何在R编程语言中创建一个具有共享图例的牛图网格。

要做到这一点,首先我们要做一个基本的牛图网格,两个图分别有各自的图例。为此,我们使用R语言中的cowplot网格包,使用plot_grid()函数,并将网格中需要的所有地块作为参数传递。

语法: plot_grid(plot1,plot2,label=<label-vector>, ncol, nrow)

例子

一个基本的Cowplot网格,有两个具有独立图例的图块。

# Create sample data                           
sample_data <- data.frame(
  name = c("Geek1","Geek2","Geek3",
           "Geek4","Geeek5") ,
  value=c(31,12,15,28,45))
  
# Load ggplot2 and cowplot
library("ggplot2") 
library("cowplot")
  
# Create both plot and store in variable
plot1<-ggplot(sample_data, aes(x=name, y=value, fill=name)) +
        geom_bar(stat = "identity")
  
plot2<-ggplot(sample_data, aes(x="", y=value, fill=name))+
        geom_bar(width = 1, stat = "identity") +
        coord_polar("y", start=0)
  
# plot_grid() function adds both plots in a cowplot grid
plot_grid(plot1, plot2)

输出

R语言中牛图网格的共享图例

共享图例牛津图网格

要创建带有共享图例的cowplot网格,没有内置的方法,但可以通过以下步骤实现这一功能。

第1步: 用以下方法创建要放在网格中的没有图例的图块。

plot + theme(legend.position = "none")

第2步: 现在用plot_grid()函数将两幅图结合起来,并将其存储在一个变量中。

combined_plot<-plot_grid(plot1, plot2, ...... ncol)

第3步: 现在我们从上面的一个图中提取图例,把它放在组合图中使用。

legend <- get_legend( plot1 )

第4步: 最后用plot_grid函数将组合图与派生图例结合起来,以获得共享图例图的理想外观。

plot_grid(combined_plot, legend, ncol)

例子

这里,是上述方法的一个实现,以获得一个具有共享图例的牛图格。

# Create sample data                           
sample_data <- data.frame(
  name = c("Geek1","Geek2","Geek3",
           "Geek4","Geeek5") ,
  value=c(31,12,15,28,45))
  
# Load ggplot2 and cowplot
library("ggplot2") 
library("cowplot")
  
# Create both plot without legend and store in variable
plot1<-ggplot(sample_data, aes(x=name, y=value, fill=name)) +
        geom_bar(stat = "identity")+
        theme(legend.position = "none")
  
plot2<-ggplot(sample_data, aes(x="", y=value, fill=name))+
        geom_bar(width = 1, stat = "identity") +
        coord_polar("y", start=0)+
        theme(legend.position = "none")
  
# combine both plot using plot_grid()
combined_plot<-plot_grid(plot1, plot2,ncol=2)
  
# extract legend from plot1
legend <- get_legend(
  plot1 +
    guides(color = guide_legend(nrow = 1)) +
    theme(legend.position = "bottom")
)
  
# Combine combined plot and legend using plot_grid()
plot_grid(combined_plot, legend,ncol=1,rel_heights = c(1, .1))

输出

R语言中牛图网格的共享图例

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程