我有2个直方图,我想合并成一个图。我不知何故不能将它们两者加在一起。一个数据帧的长度为1000,另一个数据帧的长度为1000。
以下代码给我一个错误:
Error: `mapping` must be created by `aes()`
如何将它们与图例结合在一起?
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))
各个直方图如下:
任何帮助将不胜感激。谢谢
编辑:
prediction_2b$value <- 'prediction_2b'
prediction_3$value <- 'prediction_3'
combined_pred <- rbind(prediction_2b, prediction_3)
出现错误:
Error in match.names(clabs, names(xi)) : names do not match previous names
答案 0 :(得分:2)
由于没有您的数据,使用一些虚假数据怎么办?
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))
这里是分开的地块:
ggplot(prediction_3)+
geom_histogram(aes(x=prediction_3), binwidth = 0.01)
ggplot(prediction_2b)+
geom_histogram(aes(x=prediction), binwidth = 0.01)
要将它们绘制在一起,您可以在此处以长格式手动将它们融化:
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)
答案 1 :(得分:0)
尝试将2个data.frame与指示其差异的变量组合在一起。
如果两个data.frame predition_3
和prediction_2b
具有相同的列名,则可以执行以下操作:
prediction_3$prediction_no <- '3'
prediction_2b$prediction_no <- '2b'
prediction.table <- rbind(prediction_2b, prediction_3)
然后,您可以使用fill
美观度将数据分为2个直方图:
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)