Reputation: 85
I want to plot some diagrams beside each other (e.g. in columns) and write them to one png file. In graphics::plot
it works with layout(...)
, but how do I arrange diagrams in ggplot2
?
Is there something I can do with facets?
Example:
require(cars)
require(data.table)
require(tidyr)
df <- as.data.table(mtcars)
df$obs <- seq_len(df[,.N])
df <- as.data.table(pivot_longer(data = df, names_to = "name", values_to = "val", cols = names(df[, !"obs"])))
df[, name := as.factor(name)]
library(ggplot2)
g <- ggplot(data = df)
g <- g + aes(x = df[, obs], y = df[, val])
g + facet_wrap(df[, name]) + geom_line()
It is not perfect. This gives me a matrix of diagrams for all properties of mtcars
. But the y axis is always set to the maximum of the largest value of all properties.
I want the y axis to have the optimum range for each property.
Another thing is, how to plot different tables in the same file:
df1 <- as.data.table(mtcars)[, 1]
df1$obs <- seq_len(df1[,.N])
df2 <- as.data.table(mtcars)[, 2]
df2$obs <- seq_len(df2[,.N])
g1 <- ggplot(data = df1)
g1 <- g1 + aes(x = df1[, obs], y = df1[, mpg])
g1 + geom_line()
g2 <- ggplot(data = df2)
g2 <- g2 + aes(x = df2[, obs], y = df2[, cyl])
g2 + geom_line()
How can I arrange my plots? I don't want them to be plotted in the same diagram. They should have their own axes and titles.
Upvotes: 1
Views: 959
Reputation: 73702
Just free your scale using scales="free"
option.
g + facet_wrap(df[, name], scales="free") + geom_line()
For your second question, you may want to consult this answer: Side-by-side plots with ggplot2
Upvotes: 1