繁体   English   中英

用两个y轴在R中绘图

[英]Plotting in R with two y-axes

所以我有一个如下所示的数据框:

在此输入图像描述

我试图绘制这个,以便'癌症'在x轴上,然后'oddsRatio'和'foldIncrease'都是y轴参数。 理想情况下,我有一个条形图,其中oddsRatio和foldIncrease用于彼此相邻的每个癌症,并通过颜色区分。

这是我能得到的最接近的:

在此输入图像描述

使用以下代码:

cancers = c("All Cancers", "SCLC", "Lu SCC", "Lung AC", "Larynx", "Pharynx Oral", "Cavity", "Esophageal SCC", "Esophageal AC", "Bladder", "Liver", "Cervix", "Kidney", "Pancreas")
oddsRatio = c(1, 111.3, 103.5, 21.9, 13.2, 6.6, 4.2, 3.9, 3.9, 3.8, 2.9, 1.8, 1.7, 1.6)
foldIncrease = c(1.15464695360441, 0.858680717668245, 1.29986125563649, 4.56755645705811, 2.52922152922153, 0.818596228001855, 0.892133516869108, 1.04842410881178, 1.01791768793961, 1.1423932173087, 1.1871100629828, 0.857694671793762, 1.39573948596081, 1.33458517681876)

cancerData = data.frame(cancers, oddsRatio, foldIncrease)

par(mar = c(5,5,2,5))
with(cancerData, plot(cancers, oddsRatio, type="scatter", col="red3", 
             ylab='Odds Ratio',
             ylim=c(0,150)))

par(new = T)
with(cancerData, plot(cancers, foldIncrease, pch=16, axes=F, xlab=NA, ylab=NA, cex=1.2))
axis(side = 4)
mtext(side = 4, line = 3, 'Fold Increase')

澄清我正在寻找这个:

在此输入图像描述

这是你想要的吗? (注意,我使用的是ggplot2而不是base

library(tidyverse)
tidy <- cancerData %>% 
    gather(stats, val, -cancers)

ggplot(tidy, aes(cancers, val)) + 
    geom_bar(aes(fill = stats), stat = "identity", position = "dodge")

在此输入图像描述

编辑

好的,所以我认为这不是一个好主意。 这里是为什么。 但如果你真的想,下面应该为你做。

vars <- length(unique(cancerData$cancer))

par(mar = c(4, 4, 4, 6))
plot(1:vars, seq(0, 120, length = vars), 
    type = "n",
    main = "Odds Ratios and Fold Increase",
    bty = "n",
    xaxt = "n",
    xlab = "Cancers",
    ylab = "Odds Ratios")
rect(1:vars - 0.25, 0, 1:vars, cancerData$oddsRatio, col = "blue")
axis(1, at = 1:vars, labels = unique(cancerData$cancer))

par(new = TRUE)
plot(1:vars, seq(0, 5, length = vars), 
    type = "n", 
    xaxt = "n", 
    yaxt = "n",
    bty = "n",
    xlab = "",
    ylab = "")
rect(1:vars, 0, 1:vars + 0.25, cancerData$foldIncrease, col = "red")
axis(4)
mtext("Fold Increase", side = 4, line = 3)
legend("topright", 
    fill = c("blue", "red"), 
    legend = c("Odds Ratio", "Fold Increase"),
    box.lwd = 0)

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM