How to Separate Two Plots in R

How to create plots in multiple windows and keep them separate in R

This works fine if you remove the line with dev.off().

Create separate plots from one tibble and save each plot separately in R

Without resorting to additional packages like ggforce, you could write a function to plot and save the graph for a single country like so:

plot_country <- function(x = "Aus") {
tmp <- sect_balances %>%
filter(Country == x)
p <- ggplot(tmp, aes(x = Year, y = Value, fill = Sector)) +
geom_bar(position = "stack", stat = "identity") +
labs(x = "Year", y = "Per cent of GDP", title = x) +
theme_classic()
ggsave(p, file=paste0(x, ".png"))
}

Then just loop over country names:

for (k in unique(sect_balances$Country)) {
plot_country(k)
}

The embrace operator is described in the "programming with dplyr" vignette:

https://dplyr.tidyverse.org/articles/programming.html

Simpler code to generate multiple plots in R based on column values?

The simplest way to do this is with facet_wrap, but that will put all your plots on one page, which won't work if you have lots of IDs. Instead, you could create all your plots and store them in a list:

library(ggplot2)

df <- data.frame(ID = c(1, 1, 2, 2, 3, 3, 4, 4),
var1 = c('a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'),
var2 = c(2000, 2001, 2000, 2001, 2000, 2001, 2000, 2001),
var3 = c(1:8))

plot_list <- lapply(split(df, df$ID), function(x)
{
ggplot(x, aes(var2, var3)) +
geom_line() +
geom_point()
})

Now you can plot them as easily as:

plot_list[[1]]

Sample Image

plot_list[[2]]

Sample Image

plot_list[[3]]

Sample Image

plot_list[[4]]

Sample Image

Or you can save them to file with a simple loop:

for(i in seq_along(plot_list)) ggsave(paste0("plot_", i, ".png"), plot_list[[i]])

Which will save all four plots as files named "plot_1.png" to "plot_4.png" in your working directory.

Created on 2020-08-12 by the reprex package (v0.3.0)

Make multiple separate plots from single data frame in R

It seems that you would like to do something similar to the following. If I missunderstood your question, please revise your question. You may also want to provide data from more than one park, zone and year.

# load packages
require(ggplot2)
require(plyr)
# read data
Y <- read.table("C:/data.csv", sep=",", header=TRUE)
# define the theme
th <- theme_bw() +
theme(axis.text.x=element_text(),
axis.line=element_line(colour="black"),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background=element_blank(),
legend.justification=c(10,10), legend.position=c(10,10),
legend.title = element_text(),
legend.key = element_blank()
)
# determine park levels
parks <- levels(Y[,"Park_name"])
# apply seperately for each park
p <- lapply(parks, function(park) {
ggplot(Y[Y[, "Park_name"]==park,], aes(x=as.factor(Year), y=Height_mm)) +
facet_grid(Zone~.) + # show each zone in a seperate facet
geom_point() + # plot the actual heights (if desired)
# plot the mean and confidence interval
stat_summary(fun.data="mean_cl_boot", color="red")
})
# finally print your plots
lapply(p, function(x) print(x+th))

How to split dataframe into different plots in R?

Plotting functions in the lattice package have a formula interface whose | operator allows you to indicate a conditioning variable used to split the data into a "lattice" or "trellis" of separate plots.

Try this, for example:

## Read in your data
df <- read.table(text="latency1, latency2, testType
1.3233831,1.0406423,A
1.6799337,1.1520619,A
1.6301824,1.1536479,B
2.3465363,1.2346457,C
1.2452355,1.9987547,C", header=T, sep=",")


library(lattice)
xyplot(latency2 ~ latency1 | testType, data = df, type = "b")

Plot multiple graphs from multiple csv and follow up analysis

I am not sure that the following is what the question is asking for.

The main method is always the same,

  1. split the data with base function split. This creates a named list;
  2. pipe the resulting list to seq_along to get index numbers into the list. This allows for access to the list's names attribute and to compose filenames according to them;
  3. pipe the numbers to purrr::map and plot each list member separately;
  4. save the results to disk.

First load the packages needed.

suppressPackageStartupMessages({
library(dplyr)
library(ggplot2)
library(purrr)
})

This is a common function to save the plots.

save_plot <- function(graph, graph_name, type = "") {
# file name depends on suffix and on directory structure
# the files are to be saved to a temp directory
# (it's just a code test)
if(type != "")
graph_name <- paste0(graph_name, "_", type)
filename <- paste0(graph_name, ".pdf")
filename <- file.path("~/Temp", filename)
ggsave(filename, graph, device = "pdf")
}

1. Plot all graphs separately

From the question:

It works fine except I need to save all the graphs separately.

Does this mean that the graphs corresponding to each file are to be saved separately? If yes, then the following code plots and saves them in files with filenames with the extension .csv changed to .pdf.

list_dfs_by_fname <- split(one_big_df, one_big_df$fname)
list_dfs_by_fname %>%
seq_along() %>%
map(.f = \(i) {
graph_name <- names(list_dfs_by_fname)[i]
DF <- list_dfs_by_fname[[i]]

graph <- DF %>%
ggplot(aes(x = x, y = y)) +
geom_point()

save_plot(graph, graph_name)
})


2. Plot by suffix

First create a new column with either the suffix "B3" or the suffix "B4". Then split the data by groups so defined. The split data is needed for the two plots that follow.

inx <- grepl("B4$", one_big_df$fname)
one_big_df$group <- c("B3", "B4")[inx + 1L]
list_dfs_by_suffix <- split(one_big_df, one_big_df$group)

2.1. Plot by suffix, overlapped

To have the groups of fname overlap, map that variable to the color aesthetic.

list_dfs_by_suffix %>% 
seq_along() %>%
map(.f = \(i) {
graph_name <- names(list_dfs_by_suffix)[i]
DF <- list_dfs_by_suffix[[i]]

graph <- DF %>%
ggplot(aes(x = x, y = y, color = fname)) +
geom_point()

save_plot(graph, graph_name, type = "overlapped")
})

2.2. Plot by suffix, faceted

If the plots are faceted by fname, the code is copied and pasted from the question's with added scales = "free".

list_dfs_by_suffix %>% 
seq_along() %>%
map(.f = \(i) {
graph_name <- names(list_dfs_by_suffix)[i]
DF <- list_dfs_by_suffix[[i]]

graph <- DF %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
facet_wrap( ~ fname, scales = "free")

save_plot(graph, graph_name, "faceted")
})


Test data

Use built-in data sets iris and mtcars to test the code.

Only the last two instructions matter to the question, they check the data set one_big_df's column names and the values in fname.

suppressPackageStartupMessages({
library(dplyr)
})

df1 <- iris[3:5]
df2 <- mtcars[c("hp", "qsec", "cyl")]
names(df1) <- c("x", "y", "categ")
names(df2) <- c("x", "y", "categ")
df2$categ <- factor(df2$categ)
sp1 <- split(df1[1:2], df1$categ)
sp2 <- split(df2[1:2], df2$categ)
names(sp1) <- sprintf("MAX_C%d-B3", seq_along(sp1))
names(sp2) <- sprintf("MAX_C%d-B4", seq_along(sp2))

list_of_dfs <- c(sp1, sp2)
list_of_dfs <- lapply(seq_along(list_of_dfs), \(i) {
list_of_dfs[[i]]$fname <- names(list_of_dfs)[i]
list_of_dfs[[i]]
})
one_big_df <- list_of_dfs %>% dplyr::bind_rows()
names(one_big_df)
#> [1] "x" "y" "fname"
unique(one_big_df$fname)
#> [1] "MAX_C1-B3" "MAX_C2-B3" "MAX_C3-B3" "MAX_C1-B4" "MAX_C2-B4" "MAX_C3-B4"

Created on 2022-05-31 by the reprex package (v2.0.1)

Multiple Separate Plots on User select/multi input

As the selection allows multiple choice, you should use %in% instead of ==.

You should also use observe instead of observeEvent to react on NULL input.

library(shiny)
library(shinyjs)

shinyApp(
ui = fluidPage(
useShinyjs(), #Necessary to activate shinyjs
selectizeInput("select", "Select plot:", 1:4, multiple = TRUE),
plotOutput("p1"),
plotOutput("p2"),
plotOutput("p3"),
plotOutput("p4")
),
server = function(input, output) {
output$p1 <- renderPlot({ plot(iris) })
output$p2 <- renderPlot({ plot(mtcars) })
output$p3 <- renderPlot({ plot(0) })
output$p4 <- renderPlot({ plot(1) })

observe({
shinyjs::toggle("p1", condition = isTRUE(1 %in% input$select))
shinyjs::toggle("p2", condition = isTRUE(2 %in% input$select))
shinyjs::toggle("p3", condition = isTRUE(3 %in% input$select))
shinyjs::toggle("p4", condition = isTRUE(4 %in% input$select))
})

}
)

Merging two different Plots in R

You could use ggplot2:

library(ggplot2)

ggplot() +
geom_point(aes(x=serie_2, y=dt_frame$students, col="blue")) +
geom_point(aes(x=serie_3, y=dt_frame$numbers, col="red")) +
labs(x = "Student", y = "Grade") +
scale_color_manual(values=c("blue", "red"),
labels=c("Series 2", "Series 3"))



Related Topics



Leave a reply



Submit