 # Multiple graphs on same plot

Want to plot 5 graphs on the same plot.
Tried par(mfrow=c(2,3)) but that creates space for six graphs and the the second row graphs are not symmetric.

Hi
Sorry about not being able to present the question properly. Only have 5 graphs to plot.The above is what i am getting. But it leaves a vacant plot in the second row. I want the two graphs in the second row to be in the middle of the row and not entirely towards the left.

Tried (1,5) and (5,1), the graphs look too small.

I would use the layout function as shown below.

``````df1 <- data.frame(x = 1:4, y = 11:14)
df2 <- data.frame(x = 1:4, y = 21:24)
df3 <- data.frame(x = 1:4, y = 31:34)
df4 <- data.frame(x = 1:4, y = 41:44)
df5 <- data.frame(x = 1:4, y = 51:54)
layout(matrix(c(1,1,2,2,3,3,4,5,5,6,6,7), nrow = 2, byrow = TRUE))
plot(df1\$x, df1\$y)
plot(df2\$x, df2\$y)
plot(df3\$x, df3\$y)
plot.new()
plot(df4\$x, df4\$y)
plot(df5\$x, df5\$y)
plot.new()
`````` Created on 2019-08-18 by the reprex package (v0.2.1)

1 Like

@FJCC, thanks for showing the `layout` function. I never used it before.

I deleted my earlier posts, because you showed a much better way. Here's an update plot where those awkward `plot.new` columns are not needed. I used it of course for generating legends, but may be you can show a better way even for that? I had much difficulty in handling the height of the middle row.

``````set.seed(seed = 37714)

FakeData <- data.frame(Companies = rep(x = c("HDFC", "Infosys", "Reliance", "TataMotors", "Wipro"),
each = 60),
StockTypes = rep(x = c("Close", "High", "Low", "Open"),
times = 5,
each = 15),
Dates = rep(x = seq.Date(from = as.Date(x = "2019-06-11"),
to = as.Date(x = "2019-06-25"),
by = "day"),
times = 20),
RandomPrices = rexp(n = 300),
stringsAsFactors = FALSE)

layout(mat = matrix(data = c(1, 1, 2, 2, 3, 3, 0, 6, 6, 6, 6, 0, 0, 4, 4, 5, 5, 0),
nrow = 3,
byrow = TRUE),
heights = c(1, 0.5, 1))

lapply(X = split(x = FakeData,
f = FakeData\$Companies),
FUN = function(PerCompanyData)
{
with(data = PerCompanyData,
expr =
{
plot(x = Dates,
y = RandomPrices,
type = "n",
main = paste("Company:", unique(x = Companies)))
lapply(X = split(x = PerCompanyData,
f = PerCompanyData\$StockTypes),
FUN = function(PerStockTypeData)
{
with(data = PerStockTypeData,
expr =
{
lines(x = Dates,
y = RandomPrices,
col = match(x = unique(x = StockTypes),
table = unique(x = FakeData\$StockTypes)))
})
})
})
})

plot.new()
with(data = FakeData,
expr = legend(x = "center",
legend = unique(x = StockTypes),
col = as.factor(x = unique(x = StockTypes)),
lty = 1,
horiz = TRUE,
title = "Stock Types"))

par(par_state)
``````

This generates the following plot:

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.