使用字符循环来绘制具有特定颜色的几行 [英] Use a for-loop of characters to plot several lines with specific colors

查看:64
本文介绍了使用字符循环来绘制具有特定颜色的几行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一张图表上绘制13条线。每行代表我的数据的一个子集,按盆地列中的字符分组。我所拥有的有效,但我想使用for循环使其更有效。



问题是我不知道该如何改变每个i的颜色 i 是字符时的终止。搜索此问题可得出 i 是数字时的解决方案,或者创建所有颜色都不同的行,而这两个都不是我的目标。



这是我第一次问自己的问题,而不是在SO上的其他地方找到答案,所以让我知道您是否还有其他需要。

解决方案

在这种情况下,对于循环中的每次迭代,都需要向量的索引和变量本身。一种获得所需图的简单方法是遍历索引(在下面的示例中为 ii ),并在每次迭代时获得vector元素( i ,就像以前一样)。

  env<-data.frame(basin = c ('BLK','DUC','WHP','BLK','DUC','WHP','BLK','DUC','WHP'),
sal = c(5,6, 3,2,4,5,6,8,4),
日期= c(2013,2013,2013,2015,2015,2015,2017,2017,2017,2017))

Basinlist<-c('BLK','DUC','WHP')
图(sal〜date,data = env,type ='n',ylim = c(0,10),ylab ='盐度')

用于(ii in seq_along(basinlist)){
i<-Basinlist [ii]
行(sal [basin == i]〜date [basin = = i],数据= env,
col = c(4,4,2)[ii],
lty = c(1,1,2)[ii])
}


I would like to plot 13 lines on a single graph. Each line represents a subset of my data, grouped by the characters in column 'basin'. What I have works, but I'd like to make it more efficient using a for-loop. Here's what the output looks like.

A simplified dataframe to work with:

env <- data.frame(basin = c('BLK','DUC','WHP','BLK','DUC','WHP','BLK','DUC','WHP'),
                  sal = c(5,6,3,2,4,5,6,8,4),
                  date = c(2013,2013,2013,2015,2015,2015,2017,2017,2017))

And a simplified version of what didn't work (it runs, but makes all the lines blue and solid):

basinlist <- c('BLK','DUC','WHP')
plot(sal~date, data = env, type = 'n', ylim = c(0,10), ylab = 'Salinity')
for(i in basinlist){
  lines(sal[basin==i] ~ date[basin==i], data = env, 
        col = c(4,4,2),
        lty = c(1,1,2))
}

The issue is that I don't know how to change the colors with each iteration when i is a character. Searching for this issue yields solutions for when i is a number, or for creating lines that are all different colors, neither of which are my goal.

This is the first time I've asked my own question rather than finding the answer posted elsewhere on SO, so let me know if you need anything else.

解决方案

In this case for each iteration in your loop, you need both the index of the vector and the variable itself. An easy way to get the plot you want is to iterate over the indices (ii in the example below) and also get the vector element with each iteration (i as you had before).

env <- data.frame(basin = c('BLK','DUC','WHP','BLK','DUC','WHP','BLK','DUC','WHP'),
                  sal = c(5,6,3,2,4,5,6,8,4),
                  date = c(2013,2013,2013,2015,2015,2015,2017,2017,2017))

basinlist <- c('BLK','DUC','WHP')
plot(sal~date, data = env, type = 'n', ylim = c(0,10), ylab = 'Salinity')

for (ii in seq_along(basinlist)) {
  i <- basinlist[ii]
  lines(sal[basin==i] ~ date[basin==i], data = env,
        col = c(4,4,2)[ii],
        lty = c(1,1,2)[ii])
}

这篇关于使用字符循环来绘制具有特定颜色的几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆