📜  R中的并排饼图

📅  最后修改于: 2022-05-13 01:54:31.359000             🧑  作者: Mango

R中的并排饼图

在本文中,我们将讨论如何在 R 编程语言中并排绘制饼图。

方法 1:使用基本 R 函数

要并排绘制图形,使用 par()函数。

这些图是正常绘制的,独立于其他图。为了并排绘制它们,传递行数和列数,就像定义网格一样。



例子:

R
# Define data-set columns
x1 <- c(31,13,25,31,16)
x2 <- c(12,23,43,12,22,45,32) 
  
label1 <- c('geek','geek-i-knack','technical-scipter',
            'content-writer','problem-setter')
label2 <- c('sun','mon','tue','wed','thur','fri','sat')  
  
# set the plotting area into a 1*2 array
par(mfrow=c(1,2))    
  
# Draw the two pie chart using above datasets
pie(x1, label1,main="Students per Event", col=rainbow(length(x1)))
pie(x2, label2,main="Students per day in a week")


R
# Define data-set columns
x1 <- c(31,13,25,31,16)
x2 <- c(12,23,43,12,22,45,32) 
x3 <- c(234,123,210)
  
label1 <- c('geek','geek-i-knack','technical-scipter',
            'content-writer','problem-setter')
label2 <- c('sun','mon','tue','wed','thur','fri','sat')  
label3 <- c('solved','attempted','unsolved')
  
# Create data frame using above 
# data column
data1 <- data.frame(x1,label1)
data2 <- data.frame(x2,label2)
data3 <- data.frame(x3,label3)
  
# set the plotting area into a 1*3 array
par(mfrow=c(1,3))    
  
# import library ggplot2 and gridExtra
library(ggplot2)
library(gridExtra)
  
# Draw the two pie chart using above datasets
plot1<-ggplot(data1, aes(x="", y=x1, fill=label1)) +
geom_bar(stat="identity", width=1) + 
coord_polar("y", start=0)
  
plot2<-ggplot(data2, aes(x="", y=x2, fill=label2)) + 
geom_bar(stat="identity", width=1) + 
coord_polar("y", start=0)
  
plot3<-ggplot(data3, aes(x="", y=x3, fill=label3)) +
geom_bar(stat="identity", width=1) + 
coord_polar("y", start=0)
  
# Use grid.arrange to put plots in columns
grid.arrange(plot1, plot2, plot3, ncol=3)


输出:

方法二:使用ggplot2

在此 grid.arrange() 中用于在框架上排列图。

在这里,绘图是正常且独立地绘制的。然后,以定义网格的方式使用这些图以及行数和列数调用该函数。

例子:

电阻

# Define data-set columns
x1 <- c(31,13,25,31,16)
x2 <- c(12,23,43,12,22,45,32) 
x3 <- c(234,123,210)
  
label1 <- c('geek','geek-i-knack','technical-scipter',
            'content-writer','problem-setter')
label2 <- c('sun','mon','tue','wed','thur','fri','sat')  
label3 <- c('solved','attempted','unsolved')
  
# Create data frame using above 
# data column
data1 <- data.frame(x1,label1)
data2 <- data.frame(x2,label2)
data3 <- data.frame(x3,label3)
  
# set the plotting area into a 1*3 array
par(mfrow=c(1,3))    
  
# import library ggplot2 and gridExtra
library(ggplot2)
library(gridExtra)
  
# Draw the two pie chart using above datasets
plot1<-ggplot(data1, aes(x="", y=x1, fill=label1)) +
geom_bar(stat="identity", width=1) + 
coord_polar("y", start=0)
  
plot2<-ggplot(data2, aes(x="", y=x2, fill=label2)) + 
geom_bar(stat="identity", width=1) + 
coord_polar("y", start=0)
  
plot3<-ggplot(data3, aes(x="", y=x3, fill=label3)) +
geom_bar(stat="identity", width=1) + 
coord_polar("y", start=0)
  
# Use grid.arrange to put plots in columns
grid.arrange(plot1, plot2, plot3, ncol=3)

输出: