@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)
par_state <- par(no.readonly = TRUE)
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: