堆叠条形图与 R 中的线 [英] Stacked Barplot together with Line in R

查看:43
本文介绍了堆叠条形图与 R 中的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下堆叠条形图一起制作与线曲线.

I want to make the following stacked bar plot together with line curve.

但是为什么下面的代码不起作用?正确的做法是什么?

But why this following code does not work? What's the right way to do it?

x<-c(0,1,2,3,4,5,6,7,8,9,10,11,12);

    # To plot line 
    emp_dens <- c(0.107,0.184,0.205,0.185,0.138,0.091,0.049,0.023,0.01,0.0028,0.0012,0.00023,0.00013);
    dat_dens <- as.matrix(cbind(x,emp_dens));


    # To plot stack bar
    dens_all_k <- c(1.15e-01, 1.89e-01, 2.05e-01, 1.82e-01,1.36e-01,8.68e-02,4.71e-02,2.21e-02,9.17e-03,3.37e-03,1.11e-03,3.37e-04,9.31e-05)

    # Each k0..5 compose the stack 
    # For example
    # dens_k0[1] + .... dens_k5[1] ~= dens_all_k[1]

    dens_k0 <-c(2.52e-02,8.38e-02,1.38e-01, 1.53e-01,1.27e-01,8.44e-02, 4.66e-02, 2.21e-02, 9.16e-03, 3.37e-03,1.11e-03, 3.37e-04, 9.31e-05)
    dens_k1 <- c(6.75e-02, 8.91e-02, 5.86e-02, 2.51e-02, 8.59e-03,2.25e-03, 4.90e-04,9.35e-05, 1.55e-05,2.21e-06,2.99e-07, 3.55e-08,3.92e-09)
    dens_k2 <- c(1.70e-02,1.64e-02,7.95e-03, 2.56e-03,6.20e-04,1.20e-04, 1.93e-05, 2.67e-06, 3.23e-07,3.47e-08,3.36e-09, 2.95e-10,2.38e-11)
    dens_k3 <- c(0.005124596,0,0,0,0,0,0, 0, 0, 0, 0,0,0)
    dens_k4 <- c(0.0004270497, 0, 0,0,0, 0, 0, 0, 0,0,0, 0, 0)
    dens_k5 <- c(2.760725e-05, 0, 0, 0,0,0, 0, 0, 0, 0,0, 0,0)


    barplot(cbind(0:max(x),dens_all_k),xlim=c(0,max(x)),ylim=c(0,max(emp_dens)),,space=0.1,lwd=5,xlab="Value of X",ylab="Densities",font.main=1);
    lines(dat_dens,lty=1,col="red");

推荐答案

dens_all_k 仅包含汇总摘要.如果您正在寻找图片中的条形图,则需要提供所有 k 信息.试试下面的代码.

dens_all_k contain only the aggregate summary. If you are looking for the barplot in the picture you need to supply all k information. Try the following code.

dens_kall<-rbind(dens_k0,dens_k1,dens_k2,dens_k3,dens_k4,dens_k5)
ltext<-c("K0","K1","K2","K3","K4","K5")
colnames(dens_kall)<-0:12
barplot(height=dens_kall,xlim=c(0,max(x)),ylim=c(0,max(emp_dens)),,space=0.1,lwd=5,xlab="Value of X",ylab="Densities",font.main=1
        ,legend.text =ltext,
        args.legend = list(x = "topright")
        );
lines(dat_dens,lty=1,col="red");

输出为

这篇关于堆叠条形图与 R 中的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆