简体   繁体   中英

How to plot 2 histograms (different row lengths) in one graph (ggplot)

I have 2 histograms which i would like to combine into one plot. Somehow i cannot add both of them together. One data frame has length of 1000 and the other has a length of 1000.

The following code gives me an error:

Error: `mapping` must be created by `aes()`

How can i go about combining them with a legend?

p <-ggplot(prediction_3)+
geom_histogram(aes(x=prediction_3), binwidth = 0.01)

p + geom_histogram(prediction_2b, aes(x=prediction),binwidth = 0.01, fill = "red", alpha = 0.7)+
geom_vline(xintercept=prediction_1)+
geom_text(aes(0.5,prediction_1,label = 0.469, vjust = 1))

The individual histogram plots are as follows:

1000 values: 在此处输入图片说明

10000 values: 在此处输入图片说明

Any help will be appreciated. thank you

EDIT:

prediction_2b$value <- 'prediction_2b' 
prediction_3$value <- 'prediction_3' 
combined_pred <- rbind(prediction_2b, prediction_3)

an error appears: Error in match.names(clabs, names(xi)) : names do not match previous names

What about this, using some fake data, due there are not yours:

library(tidyverse)
# fake data
prediction_1 = 0.469

prediction_3 <- data.frame(prediction_3 = rnorm(1000, 4, 3))  
prediction_2b <- data.frame(prediction = rnorm(10000, 8, 3))

Here the separated plots:

ggplot(prediction_3)+
  geom_histogram(aes(x=prediction_3), binwidth = 0.01)

ggplot(prediction_2b)+
  geom_histogram(aes(x=prediction), binwidth = 0.01)

To plot them together, here you can manually melt them in the long format:

dats <- rbind(data.frame(pred = prediction_3$prediction_3, var = 'prediction_3'),
              data.frame(pred = prediction_2b$pred, var = 'prediction_2b'))

# here the plot
ggplot(dats, aes(pred, fill = var)) + 
  geom_histogram(alpha = 0.5, position = "identity", bins = 75) +
  geom_vline(xintercept=prediction_1) 

在此处输入图片说明

Try to combine the 2 data.frame with a variable that indicates their difference.

If the 2 data.frame predition_3 and prediction_2b have the same column names you can do:

prediction_3$prediction_no <- '3'
prediction_2b$prediction_no <- '2b'
prediction.table <- rbind(prediction_2b, prediction_3)

Then you can use the fill aesthetic to separate data into 2 histograms:

p <-ggplot(prediction.table)
p + geom_histogram(aes(x=prediction, fill=prediction_no), binwidth = 0.01, alpha=0.7)
p + scale_fill_manual(values=c('red', 'blue')) # use your own instead of default colors
p + geom_vline(xintercept=prediction_1) 
# p + geom_text(aes(0.5,prediction_1,label = 0.469, vjust = 1)) 
# I suggest to move any static assignments out of the aes() call!
# assuming that prediction_1 is a single value you can do
p + geom_text(y=0.5, y=prediction_1, label = 0.469, vjust = 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM