Quantcast
Channel: Plot two graphs in a same plot - Stack Overflow
Viewing all articles
Browse latest Browse all 18

Answer by redmode for Plot two graphs in a same plot

$
0
0

When constructing multilayer plots one should consider ggplot package. The idea is to create a graphical object with basic aesthetics and enhance it incrementally.

ggplot style requires data to be packed in data.frame.

# Data generationx  <- seq(-2, 2, 0.05)y1 <- pnorm(x)y2 <- pnorm(x,1,1)df <- data.frame(x,y1,y2)

Basic solution:

require(ggplot2)ggplot(df, aes(x)) +                    # basic graphical object  geom_line(aes(y=y1), colour="red") +  # first layer  geom_line(aes(y=y2), colour="green")  # second layer

Here + operator is used to add extra layers to basic object.

With ggplot you have access to graphical object on every stage of plotting. Say, usual step-by-step setup can look like this:

g <- ggplot(df, aes(x))g <- g + geom_line(aes(y=y1), colour="red")g <- g + geom_line(aes(y=y2), colour="green")g

g produces the plot, and you can see it at every stage (well, after creation of at least one layer). Further enchantments of the plot are also made with created object. For example, we can add labels for axises:

g <- g + ylab("Y") + xlab("X")g

Final g looks like:

enter image description here

UPDATE (2013-11-08):

As pointed out in comments, ggplot's philosophy suggests using data in long format.You can refer to this answer in order to see the corresponding code.


Viewing all articles
Browse latest Browse all 18

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>