【发布时间】:2021-01-12 16:26:04
【问题描述】:
我正在使用 R 编程语言。我在 ggplot2 中制作了几个图,现在我试图将它们安排在同一页面上:
library(dplyr)
library(ggplot2)
date= seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
var <- rnorm(731,10,10)
group <- sample( LETTERS[1:4], 731, replace=TRUE, prob=c(0.25, 0.22, 0.25, 0.25) )
data = data.frame(date, var, group)
data$year = as.numeric(format(data$date,'%Y'))
data$year = as.factor(data$year)
1) Pie Charts:
###Pie
Pie_2014 <- data %>% filter((data$year == "2014"))
Pie_2014 %>%
group_by(group) %>%
summarise(n = n())
Pie_2014_graph = ggplot(Pie_2014, aes(x="", y=n, fill=group)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +ggtitle( "Pie Chart 2014")
Pie_2015 <- data %>% filter((data$year == "2015"))
Pie_2015 %>%
group_by(group) %>%
summarise(n = n())
Pie_2015_graph = ggplot(Pie_2015, aes(x="", y=n, fill=group)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +ggtitle( "Pie Chart 2015")
Pie_total = data %>%
group_by(group) %>%
summarise(n = n())
Pie_total_graph = ggplot(data, aes(x="", y=n, fill=group)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +ggtitle( "Pie Chart Average")
Bar_years = data %>%
group_by(year, group) %>%
summarise(mean = mean(var))
Bar_years_plot = ggplot(Bar_years, aes(fill=group, y=mean, x=year)) +
geom_bar(position="dodge", stat="identity") + ggtitle("Bar Plot All Years")
Bar_total = data %>%
group_by(group) %>%
summarise(mean = n())
Bar_total_plot = ggplot(Bar_total, aes(x=group, y=mean, fill=group)) +
geom_bar(stat="identity")+theme_minimal() + ggtitle("Bar Plot Average")
New <- data %>%
mutate(date = as.Date(date)) %>%
group_by(group, month = format(date, "%Y-%m")) %>%
summarise( Mean = mean(var, na.rm = TRUE), Count = n())
#Plot
ts_1 <- ggplot(New) +
geom_line(aes(x=month, y=Mean, colour=group,group=1))+
scale_colour_manual(values=c("red","green","blue", "purple"))+
theme(axis.text.x = element_text(angle=90)) + ggtitle("time seres 1")
ts_2 <- ggplot(New) +
geom_line(aes(x=month, y=Count, colour=group,group=1))+
scale_colour_manual(values=c("red","green","blue", "purple"))+
theme(axis.text.x = element_text(angle=90)) + ggtitle("time seres 2")
在之前的帖子中:Combining Different Types of Graphs Together (R),有人(用户“monkeytennis”)向我展示了如何使用“patchwork”库来实现这一点:
# install.packages('patchwork')
library(patchwork)
(Pie_2014_graph | Pie_2015_graph | Pie_total_graph) /
(Bar_years_plot | Bar_total_plot) /
(ts_1 | ts_2)
这是完美的 - 唯一的问题是,我使用的计算机无法访问互联网或 USB 端口。我无法安装“拼凑”库。因此,我正在尝试使用“gridExtra”和“ggpubr”等库来解决同样的问题。
我想出了如何使用 ggpubr 的基本语法:
library(ggpubr)
ggarrange(Pie_2014_graph, Pie_2015_graph , Pie_total_graph, Bar_total_plot, Bar_years_plot, ts_1, ts_2)
但格式与以前不同(如拼凑而成) - 我试图将所有饼图放在一行上,将所有条形图放在一行上,并将所有时间序列放在一行上。
我也在 gridExtra 中试过这个:
library(gridExtra)
grid.arrange(Pie_2014_graph, Pie_2015_graph , Pie_total_graph, Bar_total_plot, Bar_years_plot, ts_1, ts_2)
但这会产生与之前非常相似的情节。
有人可以告诉我如何使用 ggpubr 或 gridExtra 重新创建“拼凑”答案吗?
谢谢
【问题讨论】:
标签: r ggplot2 dplyr data-visualization data-manipulation