多个geom_histogram:位置闪避问题

时间:2017-11-23 15:22:09

标签: r ggplot2 histogram

我有以下数据,POD.tbl,采用tibble格式:

   LTPOD       POD
   <dbl>     <dbl>
1 0.5423729 0.6082474
2 0.5303030 0.6055046
3 0.5614035 0.6195652
4 0.5714286 0.5957447
5 0.5714286 0.5444444
6 0.5882353 0.5795455
7 0.5961538 0.5777778
8 0.5769231 0.5714286
9 0.5593220 0.5959596
10 0.5454545 0.5945946
# ... with 4,086 more rows

我正在尝试将两列数据绘制为交错的直方图,但position =“dodge”不起作用。

示例代码:

ggplot(data=POD.tbl)+geom_histogram(mapping=aes(x=POD),binwidth=0.01,fill="red",colour="black",position="dodge")+
 geom_histogram(mapping=aes(x=LTPOD),binwidth=0.01,fill="blue",colour="black",position="dodge")+
 geom_vline(aes(xintercept=median(POD, na.rm=T),color="POD"), linetype="dashed", size=1)+
 geom_vline(aes(xintercept=median(LTPOD,na.rm=T),color="LTPOD"), linetype="dashed", size=1)+
 scale_color_manual(name = "Statistics", values = c(POD = "green", LTPOD="orange"))+
 ggtitle("POD vs LTPOD")

我得到以下情节: enter image description here

如何让这两个直方图错开?

1 个答案:

答案 0 :(得分:0)

您必须更改数据框的格式:

library(reshape2)
POD.tbl<-melt(POD.tbl)

ggplot(data=POD.tbl)+geom_histogram(mapping=aes(x=value,fill=variable),binwidth=0.5,colour="black",position="dodge")+
  geom_vline(data=aggregate(value ~ variable,POD.tbl, median),aes(xintercept=value, color=variable))+
  scale_color_manual(name = "Statistics", values = c(POD = "green", LTPOD="orange"))+
  scale_fill_manual(name = "Statistics", values = c(POD = "red", LTPOD="blue"))+
  ggtitle("POD vs LTPOD")