样本数据:
### Data
df <- data.frame(year = seq(as.Date("1998/1/1"), as.Date("2012/1/1"), "years"),
ton = sample(200:500, 15, replace = TRUE),
trend = sample(50:100, 15, replace = TRUE),
count = sample(100:200, 15, replace = TRUE))
### Load the needed libraries
library(ggplot2)
library(scales)
library(grid)
library(gridExtra)
### Make a plot
plot1 <- ggplot(data = df, aes(x = year, y = ton)) + geom_bar(stat = "identity") +
scale_x_date(breaks = df$year, labels = date_format("%Y")) +
theme_bw()
plot2 <- ggplot(data = df, aes(x = year, y = trend)) + geom_line() +
geom_point(shape = 21, size = 4, fill = "white") +
scale_x_date(breaks = df$year, labels = date_format("%Y")) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
我使用 组合了两个图grid.arrange,这里是语法:
grid.arrange(plot1, plot2, nrow = 2, top = "Sample data trend")
Run Code Online (Sandbox Code Playgroud)
我尝试了以下代码来制作表格(year和count变量,但结果不好。
### Create new dataframe for the table
df1 <- data.frame(count = df$count,
row.names = df$year)
df1 <- as.data.frame(t(df1))
### Add table below the graph
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE)))
tbl <- tableGrob(df1, rows=NULL, theme=tt)
grid.arrange(plot1, plot2, tbl,
nrow = 3,
as.table = TRUE)
Run Code Online (Sandbox Code Playgroud)
问题:如何使其适合图形区域,以及如何使表格更接近折线图,以便最小化空白区域?如果有任何方法可以自定义它?
谢谢你。
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE)),
base_size = 10,
padding = unit(c(2, 4), "mm"))
tbl <- tableGrob(df1, rows=NULL, theme=tt)
png("E:/temp/test.png", width = 1000, height = 1000)
grid.arrange(plot1, plot2, tbl,
nrow = 3, heights = c(2, 2, 0.5))
dev.off()
Run Code Online (Sandbox Code Playgroud)