Kieran Evans
Kieran Evans

Reputation: 13

How to plot multiple graphs on one plot using a different columns in a dataframe?

I have a data frame containing 4 columns, I want to plot column 1 against column 2 and column 3 against column 4 using qplot and have all the plots on the same graph, i need to extend this do a dataframe with 20 columns. Thanks for any help you can give

edit Below is an example of the data frame i'm working with:

            1         2          3          4
1  0.01795918 0.9755562 0.02040816 0.05259072
2  0.04244898 0.9455753 0.03591837 0.03864464
3  0.05224490 0.9816900 0.06122449 0.03280435
4  0.07183673 0.9635419 0.08000000 0.03453257
5  0.09551020 0.9821122 0.10040816 0.03134642
6  0.12000000 0.9354895 0.11510204 0.03920271
7  0.13877551 0.9703654 0.13877551 0.03588973
8  0.16244898 0.9506424 0.15836735 0.03402917
9  0.17224490 0.9610043 0.18530612 0.03621932
10 0.20000000 0.9863483 0.19591837 0.03021983
11 0.22122449 0.9845782 0.22530612 0.03268187
12 0.22938776 0.9835922 0.22530612 0.03513692
....

I can plot one against the other, but i need a way to plot them all onto one graph

Upvotes: 0

Views: 5677

Answers (3)

CPak
CPak

Reputation: 13581

Reproducible example

df <- data.frame(A=runif(20), B=runif(20), C=runif(20), D=runif(20))

Some data prep

Reorganize your data into

library(dplyr)
library(tidyr)
df1 <- df %>%
         gather(key, value) %>%                                       # convert everything into long format
         mutate(grp = rep(1:(ncol(df)/2), each=(nrow(df)*2))) %>%     # Each pairs of columns gets unique grouping value
         mutate(index = rep(1:nrow(df), ncol(df))) %>%                # Each observation in each group gets a unique value
         mutate(key = rep(rep(c("x","y"), each=nrow(df)), ncol(df)/2)) %>%      # label as x and y
         spread(key, value)                                           # convert to wide format again

   grp index         x          y
1    1     1 0.4820801 0.47761962
2    1     2 0.5995658 0.86120948
3    1     3 0.4935413 0.43809711
4    1     4 0.1862176 0.24479728
5    1     5 0.8273733 0.07067905
# etc

Basic ggplot solution

Uses facet_wrap to make N plots by N grp

library(ggplot2)
ggplot(data=df1, aes(x=x, y=y)) + 
  geom_point() +
  facet_wrap(~grp)

Plotting all data in one plot using geom_smooth

ggplot(data=df1, aes(x=x, y=y, colour=factor(grp))) + 
  geom_smooth()

Upvotes: 0

mnm
mnm

Reputation: 2012

Scenario: 1

To compare a single variable measured on many individuals that fall into multiple categories. In this case, I offer several univariate visualizations and plot them on a single page.

library(ggplot2)
attach(iris)

plot_1 = ggplot(iris, aes(x=Petal.Length, colour=Species)) +
  geom_density() +
  labs(title="Density plots")

plot_2 = ggplot(iris, aes(x=Petal.Length, fill=Species)) +
  geom_histogram(colour="grey30", binwidth=0.15) +
  facet_grid(Species ~ .) +
  labs(title="Histograms")

plot_3 = ggplot(iris, aes(y=Petal.Length, x=Species)) +
  geom_point(aes(colour=Species),
             position=position_jitter(width=0.05, height=0.05)) +
  geom_boxplot(fill=NA, outlier.colour=NA) +
  labs(title="Boxplots")

plot_4 = ggplot(iris, aes(y=Petal.Length, x=Species, fill=Species)) +
  geom_dotplot(binaxis="y", stackdir="center", binwidth=0.15) +
  labs(title="Dot plots")

library(gridExtra)
part_1 = arrangeGrob(plot_1, plot_2, heights=c(0.4, 0.6))
part_2 = arrangeGrob(plot_3, plot_4, nrow=2)
parts_12 = arrangeGrob(part_1, part_2, ncol=2, widths=c(0.6, 0.4))
# To save the plots 
ggsave(file="figures/plots.png", parts_12, height=6, width=10, units="in")

Multiple plots on same page

Scenario:2

Another perspective could be to mix multiple graphs on the same page. I show this below;

# Libraries required
library(ggpubr)

# Data: ToothGrowth and mtcars data sets.
# ToothGrowth
data("ToothGrowth")
head(ToothGrowth)
# mtcars 
data("mtcars")
head(mtcars)
mtcars$name <- rownames(mtcars) # add column name
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars[, c("name", "wt", "mpg", "cyl")])

# create some plots
# Box plots and dot plots using the ToothGrowth data set
# Box plot
bxp<- ggboxplot(data = ToothGrowth, x="dose", y="len",
                color = "dose", palette = "jco")
bxp
# Dot plot
dp<- ggdotplot(data = ToothGrowth, x="dose", y="len",
               color = "dose", palette = "jco", binwidth = 1)
dp

# Bar plots and scatter plots using the mtcars data set
# Create an ordered bar plot by changing the fill color by the grouping variable “cyl”. Sorting will be done globally, but not by groups.
bp <- ggbarplot(mtcars, x = "name", y = "mpg",
                fill = "cyl",               # change fill color by cyl
                color = "white",            # Set bar border colors to white
                palette = "jco",            # jco journal color palett. see ?ggpar
                sort.val = "asc",           # Sort the value in ascending order
                sort.by.groups = TRUE,      # Sort inside each group
                x.text.angle = 90           # Rotate vertically x axis texts
)
bp + font("x.text", size = 8)
# Scatter plots (sp)
sp <- ggscatter(mtcars, x = "wt", y = "mpg",
                add = "reg.line",               # Add regression line
                conf.int = TRUE,                # Add confidence interval
                color = "cyl", palette = "jco", # Color by groups "cyl"
                shape = "cyl"                   # Change point shape by groups "cyl"
)+
  stat_cor(aes(color = cyl), label.x = 3)       # Add correlation coefficient
sp

# Arrange on one page
# We will use the ggarrange() [in ggpubr]
ggarrange(bxp, dp, bp + rremove("x.text"), 
          labels = c("A", "B", "C"),
          ncol = 2, nrow = 2)
# Alternatively, you can also use the function grid.arrange()[in gridExtra]

# Annotate the arranged figure R function: annotate_figure() [in ggpubr]
figure <- ggarrange(sp, bp + font("x.text", size = 10),
                    ncol = 1, nrow = 2)
annotate_figure(figure,
                top = text_grob("Visualizing mpg", color = "red", face = "bold", size = 14),
                bottom = text_grob("Data source: \n mtcars data set", color = "blue",
                                   hjust = 1, x = 1, face = "italic", size = 10),
                left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90),
                right = "I'm done, thanks :-)!",
                fig.lab = "Figure 1", fig.lab.face = "bold"
)

# Change column/row span of a plot
# We’ll use nested ggarrange() functions to change column/row span of plots.
ggarrange(sp,                                                 # First row with scatter plot
          ggarrange(bxp, dp, ncol = 2, labels = c("B", "C")), # Second row with box and dot plots
          nrow = 2, 
          labels = "A"                                        # Labels of the scatter plot
) 

anotherexampleformultipleplots

Upvotes: 2

Rafał B.
Rafał B.

Reputation: 147

You can use basic plot system and before plot anything assign how many graphs you want :

par(mfrow = c(1,2)

This is equal to plot graphs with 1x2

I don't know how your data frame look like but the simplest way is make something like this : set.seed(123) df <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100), c = rnorm(100)) plot(df$x, df$y) plot(df$z, df$c)

Upvotes: 1

Related Questions