将ECDF图与直方图结合在辅助轴ggplot中

我有一个收入变量。我想在两个Y轴的一个图中绘制直方图和累积分布的组合图。我得到了这段代码,

income<-  bi_tr%>%
  ggplot(aes(x=`12 Income`,na.rm = TRUE))+ #this fill comment goes to define legend
  geom_histogram(binwidth=50)+ #setting default color for aes in histogram
  theme_classic()+
  geom_line(stat = "ecdf")+
  geom_point(stat="ecdf",size=2)+
  scale_y_continuous(sec.axis = sec_axis(trans = ~./max(bi_tr$`12 Income`),
                                         name = "Cumulative distribution (%)"))+
  labs(x="Income (USD/month)",y="Frequency")+
  theme(text = element_text(size = 16, family = "serif"))+
  xlim(0,500)

Then after I run income it returns this plot enter image description here

Personally, I have found some similar references with built-in function in R (without ggplot) for this case. But, somehow I want to stick with ggplot instead, hoping I could cope with the same syntax pattern for more cases afterwards. Then, I found trans=~./max(data) line that works for ggplot. Then I tucked with this result.

非常感谢

评论