简体   繁体   English

R-如何从布尔值绘制图形

[英]R - How to plot a graph from bool values

So, I have a vector full of 1s and 0s. 因此,我有一个充满1和0的向量。 I need to plot a graph that starts at (0, 0) and rises by 1 for every 1 in the vector and dips by 1 for every 0 in the vector. 我需要绘制一个图,该图从(0,0)开始,向量中每1上升1,向量中每0下降1。 For example if my vector is [ 1, 1, 1, 0, 1, 0, 1, 1 ] I should get something that looks like 例如,如果我的向量是[1,1,1,0,1,0,1,1],我应该得到类似

在此处输入图片说明

I thought about creating another vector that would hold the sum of the first i elements of the original vector at index i (from the example: [ 1, 2, 3, 3, 4, 4, 5, 6 ]) but that would not account for the dips at 0s. 我考虑过要创建另一个向量,该向量将在索引i处保留原始向量的前i个元素的总和(例如:[1,2,3,3,4,4,5,6]),但是不会占0s的骤降。 Also, I cannot use loops to solve this. 另外,我不能使用循环来解决这个问题。

I would convert the zeros to -1, add a zero at the very beginning to make sure it starts from [0,0] and then plot the cumulative sum: 我将零转换为-1,在开始时添加一个零以确保它从[0,0]开始,然后绘制累积和:

#starting vec
myvec <- c(1, 1, 1, 0, 1, 0, 1, 1)
#convert 0 to -1
myvec[myvec == 0] <- -1
#add a zero at the beginning to make sure it starts from [0,0]
myvec <- c(0, myvec)
#plot cumulative sum
plot(cumsum(myvec), type = 'line')
#points(cumsum(myvec)) - if you also want the points on top of the line

在此处输入图片说明

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

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