R:如何在y轴上绘制两个数据集作为log10刻度和y2辅助轴

时间:2019-05-31 15:40:25

标签: r plot

我想在log10刻度的左侧Y轴上绘制列A和B,在法线轴上的右侧轴上绘制列C。 x轴应为“时间”表的第1列。

我的数据是:

数据

A tibble: 7 x 4

      Time A B C
        <dbl>         <dbl>    <dbl> <dbl>
    1       1        33046.     196.  0.81
    2       2       970250      578.  0.94
    3       3      1870125      323.  2.31
    4       4       259625      509. 12.2 
    5       5      3838750      215. 11.5 
    6       6       962333.    5437.  4.7 
    7       7      2272917.   41028. 10.1

我尝试过:

plot(data$Time, data$A, type = "l",  xlim = NULL, ylim = NULL,
     log = "y", main = "Title", xlab = "Time", ylab = "copies", col= "blue")
par(new = TRUE)
plot(data$Time, data$B, type = "l",  xlim = NULL, ylim = NULL,
     log = "y", main = "", xlab = "", ylab = "", col= "green", add=TRUE)
par(new = TRUE)
plot(data$C, type = "l", xaxt = "n", yaxt = "n",
     ylab = "", xlab = "", col = "red", lty = 2, )
axis(side = 4)
mtext("secondary axis", side = 4, line = 3)
legend("topleft", c("A", "B", "C"),
       col = c("blue", "green", "red"), lty = c(1, 2)) 
  • 如何在y1上以对数刻度(10 ^ 2-10 ^ 6)绘制A和B而不重叠?
  • 如何添加y2轴标题?

图:

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要为两个图指定相同的限制以具有相同的轴。这就是为什么我在两个图中都有ylim = c(100,10000000)

您需要定义适当的边距并绘制边界以显示所有内容。这就是par(mar = c(5,4,4,4) + 0.1)的作用。

legend中,您需要为所有迹线指定线型。因此,lty = c(1, 2)是不正确的,因为使B的轨迹在图例中变为虚线,而C为虚线。我为此使用了lty = c(1, 1, 2)

此外,我在col="red"中使用了mtext,以明确指出辅助轴是C的地方,也是red中的东西。

data <- structure(list(Time = 1:7, 
                          A = c(33046, 970250, 1870125, 259625, 3838750, 962333, 2272917), 
                          B = c(196, 578, 323, 509, 215, 5437, 41028), 
                          C = c(0.81, 0.94, 2.31, 12.2, 11.5, 4.7, 10.1)), 
                  row.names = c(NA, -7L), 
                  class = c("tbl_df", "tbl", "data.frame"))

opar <- par(mar = c(5,4,4,4) + 0.1)

plot(data$Time, data$A, type = "l",  xlim = NULL, ylim = c(100,10000000),
     log = "y", main = "Title", xlab = "Time", ylab = "copies", col= "blue")

par(new = TRUE)
plot(data$Time, data$B, type = "l",  xlim = NULL, ylim = c(100,10000000),
     log = "y", main = "", xlab = "", ylab = "", col= "green")

par(new = TRUE)
plot(data$C, type = "l", xaxt = "n", yaxt = "n",
     ylab = "", xlab = "", col = "red", lty = 2, )
axis(side = 4)

mtext("secondary axis", side = 4, line = 3, col="red")
legend("topleft", c("A", "B", "C"),
       col = c("blue", "green", "red"), lty = c(1, 1, 2)) 
par(opar)

reprex package(v0.3.0)于2019-06-03创建