1

I have 2 datasets, called A and B. I want to compare the distribution of one common variable, called k, showing up in both dataset, but of different lengths (A contains 2000 values of k, while B has 1000, both have some N/A). So I would like to plot the distribution of A$k anf B$k in the same plot.

I have tried:

g1 <- ggplot(A, aes(x=A$k)) + geom_density()
g2 <- ggplot(B, aes(x=B$k)) + geom_density()
g <- g1 + g2

But then comes the error:

Don't know how to add o to a plot.

How can I overcome this problem?

2
  • 2
    When making plots with ggplot, avoid using $. Also you should merge your data sets by either using a common ID or creating one. Or use the new data set in an aes call to a geom ie inside one geom_density use data=data2,aes..... eg ggplot(A, aes(x=k)) + geom_density()+geom_density(data=B,aes(x=k) You should however make your question reproducible. Commented Apr 28, 2019 at 5:43
  • With cowplot: cran.r-project.org/web/packages/cowplot/vignettes/… Commented Apr 28, 2019 at 18:56

2 Answers 2

3

Since we dont have any data it is hard to provide a specific solution that meets your scenario. But below is a general principle of what I think you trying to do.

The trick is to put your data together and have another column that identifies group A and group B. This is then used in the aes() argument in ggplot. Bearing in mind that combining your data frames might not be as simple as what I have done since you might have some extra columns etc.

# generating some pseudo data from a poisson distribution
A <- data.frame(k = rpois(2000, 4))
B <- data.frame(k = rpois(1000, 7))

# Create identifier
A$id <- "A"
B$id <- "B"

A_B <- rbind(A, B)

g <- ggplot(data = A_B, aes(x = k, 
                            group = id, colour = id, fill = id)) + # fill/colour aes is not required
  geom_density(alpha = 0.6) # alpha for some special effects

g
Sign up to request clarification or add additional context in comments.

Comments

0

I can't tell you exactly that to do without knowing what data sets actually look like. But merging data sets into one then use ggplot() by specifying group or 'colour' would be one way to compare.

Another way is to use grid.arrange() from gridExtra package.

gridExtra::grid.arrange(g1, g2)

This is really easy and pretty convenient function. If you want to know more about gridExtra package, visit this official document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.