如何:在 R 中多条彩色绘图线加上两条 y-axis

How to: Multiple colored plot lines plus two y-axis in R

我是 R 的新手,一点线索都没有,先说明一下。

我有一个 csv 文件保存到 data 和 header Cycle,Instances,MaxFitness,MinFitness 其中循环只是对行进行编号,实例经过 0 到 100 之间的正弦曲线,适应度值在 0.5 到 5 之间。

所需的输出是单个 svg 或 pdf 文件,其中我在 x 轴上有循环,在左侧 y 轴上有适合度,在右侧 y 轴上有实例。除此之外,我需要为最小值、最大值和实例单独着色 plot-line。

我一直在研究 plot、xyplot 等等,但通常会遗漏一些东西,让它成为 "color"、"all in one diagramm" 之类的东西。

如果有人能阐明这个问题,那就太好了。

没有任何 MWE,我创建了一个:

# Create two series with different scales
# Your Cycle is then the index, from 1 to 20
x1 = runif(20, 0, 100)
x2 = runit(20, 0.5, 5)
# Plot them and add specific y axis
plot(x1/100, type ="l", yaxt ="n", ylab ="", ylim = c(0,1))
lines((x2-0.5)/4.5, col = 2)
axis(side = 2, at = c(0.2, 0.8), labels = c(20, 80))
axis(side = 4, at = c(0.5), labels = c(2.75))

所以结果是

我使用了包 plotly

这是代码(我的数据与你的描述不符,但足以显示代码)。

library("plotly")

set.seed(123)

df <- data.frame(
  Cycle=c(1:10)
  , Instances=runif(10,0,100)
  , MaxFitness=runif(10,0.5,5)
  , MinFitness=runif(10,0.5,5)
)


######
## Plot
p <- plot_ly(data = df) %>%
  add_lines(x=~Cycle, y=~MaxFitness, color="blue", name="MaxFitness") %>%
  add_lines(x=~Cycle, y=~MinFitness, color="green", name="MinFitness") %>%
  add_lines(x=~Cycle, y=~Instances, color="red", name="Instances", yaxis="y2") %>%

  layout(

    title = "Double Y Axis Example",
    yaxis=list(
      title = "left y axis"
    ),
    yaxis2=list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "right",
      title = "right y axis"
    )

  )
p

这是输出:

现在您可以根据自己的喜好编辑整个情节。