【问题标题】:How to: Multiple colored plot lines plus two y-axis in R如何:多条彩色绘图线加上 R 中的两个 y 轴
【发布时间】:2017-04-20 15:57:20
【问题描述】:

我是 R 新手,没有一点线索,请先说明这一点。

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

所需的输出是单个 svg 或 pdf 文件,其中我有 x 轴上的循环,左侧 y 轴上的适应度和右侧 y 轴上的实例。除此之外,我还需要一条单独着色的最小、最大和实例的绘图线。

我已经在 plot、xyplot 等方面搞了一段时间了,但通常会缺少一些东西,让它成为“颜色”、“all in one diagramm”之类的东西。

如果有人能对这个问题有所了解,那就太棒了。

【问题讨论】:

  • 我认为最快的解决方法是使用带有标准化数据的基本图,然后相应地手动添加 y 轴
  • 你能给我们你的head(data)吗?

标签: r plot colors axis


【解决方案1】:

我使用了 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

这是输出:

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

【讨论】:

    【解决方案2】:

    没有任何 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))
    

    所以结果是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-07
      • 2019-07-29
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多