【问题标题】:Combining 2 plots into 1 plot in R在 R 中将 2 个图合并为 1 个图
【发布时间】:2021-01-18 22:14:18
【问题描述】:

我想在一个地块上绘制 2 个地块。下面是创建图的代码。情节已创建,但我试图将它们放在同一个情节上。我不认为这些图是 [plots] 或 [ggplots] 类型。谢谢。

library("fPortfolio")
library('fPortfolio')
data = SPISECTOR.RET
asset = dim(data)[2]

constraints <- c('minW[1:asset]=0','maxW[1:asset]=0.3')
spec <- portfolioSpec()
setNFrontierPoints(spec) <- 25
setSolver(spec)<- "solveRquadprog"

frontier <-portfolioFrontier(data, spec, constraints)

Pont <- 6

#I don't know if GGplot is needed
library(ggplot2)

#plot First Point [I don't think this is a ggplot]
plot1 <- weightsPie(object = frontier, pos = Pont, labels = F, col = rainbow(asset),
                    box = F, legend = F, radius = 0.8)

#plot Second Point [I don't think this is a ggplot]
plot2 <- weightsPie(object = frontier, pos = Pont, labels = T, col = rainbow(asset),
                    box = TRUE, legend = T, radius = 0)

#I want to Put the two plots on the same plot
library("gridExtra")
grid.arrange(plot1, plot2, nrow=1, ncol=2)

【问题讨论】:

  • class(plot1) 返回什么?如果它不包括 ggplot,你是对的 - 它们不是 ggplots,grid.arrange 将不起作用
  • 它显示为numeric。我想要做的就是将两个地块放入 1 个地块中。谢谢。

标签: r ggplot2 plot pie-chart


【解决方案1】:

我知道是base R,但它至少显示了一些输出。 我使用layout 来安排地块:

# your previous code

layout(matrix(c(1, 2), nrow = 1, byrow = TRUE))
layout.show(n=2)

plot1 <- weightsPie(object = frontier, pos = Pont, labels = F, col = rainbow(asset),
                    box = F, legend = F, radius = 0.8)

plot2 <- weightsPie(object = frontier, pos = Pont, labels = T, col = rainbow(asset),
                    box = TRUE, legend = T, radius = 0) 

这里是输出:

"Arrangement"

【讨论】:

  • 谢谢,我将nrow 重新排列为ncol,效果很好。我可以将它保存为 R 中的图(使用 ggplot)吗?
  • 您可以手动保存它:导出 -> ... 或者可以这样做:pdf("arrangement", onefile = FALSE) 然后放置您的布局和绘图命令,然后以 dev.off() 结束。您的绘图将存储到您的工作目录中。您可以将 pdf 更改为其他内容,例如。 G。如果你愿意,可以选择png。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多