如何用R绘制双坐标图?

Python028

如何用R绘制双坐标图?,第1张

library(plotrix)

twoord.plot(lx,ly,rx,ry,data=NULL,main="",xlim=NULL,lylim=NULL,rylim=NULL,

mar=c(5,4,4,4),lcol=1,rcol=2,xlab="",lytickpos=NA,ylab="",ylab.at=NA,

rytickpos=NA,rylab="",rylab.at=NA,lpch=1,rpch=2,

type="b",xtickpos=NULL,xticklab=NULL,halfwidth=0.4,axislab.cex=1,

do.first=NULL,xaxt="s",...)

xval1 <- seq.Date(as.Date("2017-01-02"), as.Date("2017-01-10"), by="day")

xval2 <- seq.Date(as.Date("2017-01-01"), as.Date("2017-01-15"), by="day")

going_up<-seq(3,7,by=0.5)+rnorm(9)

going_down<-rev(60:74)+rnorm(15)

twoord.plot(2:10,going_up,1:15,going_down,xlab="Sequence",

 ylab="Ascending values",rylab="Descending values",lcol=4,

 main="Plot with two ordinates - points and lines",

 do.first="plot_bg()grid(col=\"white\",lty=1)")

 axis.Date(1,xval2)

library(ggplot2)

library(gtable)

library(grid)

grid.newpage()

# two plots

p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") + theme_bw()

p2 <- ggplot(mtcars, aes(mpg, drat)) + geom_line(colour = "red") + theme_bw() %+replace% theme(panel.background = element_rect(fill = NA))

# extract gtable

g1 <- ggplot_gtable(ggplot_build(p1))

g2 <- ggplot_gtable(ggplot_build(p2))

# overlap the panel of 2nd plot on that of 1st plot

pp <- c(subset(g1$layout, name == "panel", se = t:r))

g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, pp$l, pp$b, pp$l)

# axis tweaks

ia <- which(g2$layout$name == "axis-l")

ga <- g2$grobs[[ia]]

ax <- ga$children[[2]]

ax$widths <- rev(ax$widths)

ax$grobs <- rev(ax$grobs)

ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")

g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)

g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

# draw it

grid.draw(g)

用ggplot2画个双坐标也太难了吧。。。。

d <- data.frame(name=c("zhao","qian","sun","li"),weight=c(62,58,79,60),height=c(178,169,180,173))

x <- d$name

y1 <- d$weight

y2 <- d$height

bar <- barplot(y1,xlim=c(0,5),ylim=c(0,100),ylab="Weight",col="blue",col.axis="blue",col.lab="blue")

mtext(x,side=1,line=1,at=bar,col="black")

mtext("Name",side=1,line=3,col="black")

par(new=T)    ## 创建新的画布,类似于ggplot2中的图层叠加

plot(bar,y2,axes=F,xlim=c(0,5),ylim=c(100,190),xlab="",ylab="",col="red",type="b")

axis(4,col="red",col.ticks="red",col.axis="red")

mtext("Heigth (cm)",side=4,line=3,col="red")

若画图时需要将纵坐标方向改变,可以采用取相反数的方法。正常情况下,y轴是从下往上依次增大,可以让所有数值乘以-1,使y轴从下往上依次减小,然后通过axis函数修改y轴的label。

R语言学习  绘制双坐标轴(双y轴)的方法 plotrix_瞎掰大数据_新浪博客

利用ggplot2画双坐标轴曲线

R绘制带箭头的坐标轴,两个参数需要提前设置

第一,xpd=NA,否则绘制箭头只会显示一半

xpd参数说明:A logical value or NA. If FALSE, all plotting is clipped to the plot region, if TRUE, all plotting is clipped to the figure region, and if NA, all plotting is clipped to the device region. 

第二,横纵坐标由于默认是多增加4%的区间,因此要么设置xaxs=“i" 和 yaxs ="i",让坐标轴交于结束位置

或者直接用par()['usr'][[1]] 找出绘制的起点和终点

在R语言中,这两个参数的取值包括 5种,其中"r"是默认值,就是我们上边讲到的添加4%的一个距离,"i" 代表的行为是原始数据的最小值到最大值是多少,对应的坐标轴的起始和终止位置就是多少

举例:par(xpd=NA)

plot(c(1:10),c(1:10),type="l",bty="l",xlab="X",ylab="Y")

ord<-par("usr")

arrows(x0 = ord[1],y0=ord[3],x1=ord[2]*1.05,y1=ord[3])

arrows(x0 = ord[1],y0=ord[3],x1=ord[1],y1=ord[4]*1.05)

绘制

请问大家,在运行R语言的时候,出现了以下问题,不知道是源文件的问题,还是程序的问题,求解

源文件如下

There were 50 or more warnings (use warnings() to see the first 50)

#install.packages("survival")

>library(survival)             #引用包

>inputFile="expTime.txt"       #输入文件

>pFilter=0.001                #显著性过滤条件

>setwd("C:\\Users\\ASUS\\Desktop\\tmeimmune\\22.cox")       #设置共工作目录

>#读取输入文件

>rt=read.table(inputFile,header=T,sep="\t",check.names=F,row.names=1)

>rt$futime=rt$futime/365           #以年为单位,除以365

>outTab=data.frame()

>for(gene in colnames(rt[,3:ncol(rt)])){

+     #单因素cox分析

+     cox=coxph(Surv(futime, fustat) ~ rt[,gene], data = rt)

+     coxSummary = summary(cox)

+     coxP=coxSummary$coefficients[,"Pr(>|z|)"]

+     

+     #KM检验,后续需要可视乎,要和生存相关

+     group=ifelse(rt[,gene]<=median(rt[,gene]),"Low","High")

+     diff=survdiff(Surv(futime, fustat) ~ group,data = rt)

+     pValue=1-pchisq(diff$chisq,df=1)

+     

+     #保存满足条件的基因

+     if((pValue<pFilter) &(coxP<pFilter)){

+         outTab=rbind(outTab,

+                      cbind(gene=gene,

+                            KM=pValue,

+                            HR=coxSummary$conf.int[,"exp(coef)"],

+                            HR.95L=coxSummary$conf.int[,"lower .95"],

+                            HR.95H=coxSummary$conf.int[,"upper .95"],

+                            pvalue=coxP) )

+     }

+ }

There were 50 or more warnings (use warnings() to see the first 50)

>#输出基因和P值表格文件

>write.table(outTab,file="cox.result.txt",sep="\t",row.names=F,quote=F)

>#绘制森林图

>#读取输入文件

>rt <- read.table("cox.result.txt",header=T,sep="\t",row.names=1,check.names=F)

Error in read.table("cox.result.txt", header = T, sep = "\t", row.names = 1,  : 

  no lines available in input

>gene <- rownames(rt)

>hr <- sprintf("%.3f",rt$"HR")

>hrLow  <- sprintf("%.3f",rt$"HR.95L")

>hrHigh <- sprintf("%.3f",rt$"HR.95H")

>Hazard.ratio <- paste0(hr,"(",hrLow,"-",hrHigh,")")

>pVal <- ifelse(rt$pvalue<0.001, "<0.001", sprintf("%.3f", rt$pvalue))

>#输出图形

>pdf(file="forest.pdf", width = 7,height = 6)

>n <- nrow(rt)

>nRow <- n+1

>ylim <- c(1,nRow)

>layout(matrix(c(1,2),nc=2),width=c(3,2))

>#绘制森林图左边的基因信息

>xlim = c(0,3)

>par(mar=c(4,2.5,2,1))

>plot(1,xlim=xlim,ylim=ylim,type="n",axes=F,xlab="",ylab="")

>text.cex=0.8

>text(0,n:1,gene,adj=0,cex=text.cex)

>text(1.5-0.5*0.2,n:1,pVal,adj=1,cex=text.cex)text(1.5-0.5*0.2,n+1,'pvalue',cex=text.cex,font=2,adj=1)

Error in text.default(1.5 - 0.5 * 0.2, n:1, pVal, adj = 1, cex = text.cex) : 

  'labels'长度不能设成零

>text(3,n:1,Hazard.ratio,adj=1,cex=text.cex)text(3,n+1,'Hazard ratio',cex=text.cex,font=2,adj=1,)

>#绘制森林图

>par(mar=c(4,1,2,1),mgp=c(2,0.5,0))

>xlim = c(0,max(as.numeric(hrLow),as.numeric(hrHigh)))

Warning message:

In max(as.numeric(hrLow), as.numeric(hrHigh)) :

  no non-missing arguments to maxreturning -Inf

>plot(1,xlim=xlim,ylim=ylim,type="n",axes=F,ylab="",xaxs="i",xlab="Hazard ratio")

Error in plot.window(...) : 'xlim'值不能是无限的

>arrows(as.numeric(hrLow),n:1,as.numeric(hrHigh),n:1,angle=90,code=3,length=0.05,col="darkblue",lwd=2.5)

Error in arrows(as.numeric(hrLow), n:1, as.numeric(hrHigh), n:1, angle = 90,  : 

  不能将零长度的座标同其它长度的座标混合在一起

>abline(v=1,col="black",lty=2,lwd=2)

>boxcolor = ifelse(as.numeric(hr) >1, 'red', 'green')

>points(as.numeric(hr), n:1, pch = 15, col = boxcolor, cex=1.3)

Error in xy.coords(x, y) : 'x' and 'y' lengths differ

>axis(1)

>dev.off()

null device 

          1