1

So I have an array of x and y values, and I've plotted them against each other.

But how can I plot the x values against the sum of the y values up to each x value?

I know I should probably use a for loop, but after that I'm struggling. Please see my attempt below.

import numpy as np

a = np.array([[1,1],[2,0],[3,0],[4,1],[5,4],[6,7],[7,5],[8,1],[9,2],[10,3], 
[11,10],[12,9],[13,27],[14,20],[15,39],[16,40],[17,54],[18,69],[19,74], 
[20,191],[21,126],[22,102],[23,121],[24,219],[25,204], [26,235]])

X = a[:,0]
Y = a[:,1]

plt.scatter(X,Y)
plt.show()

z = 0
for y in Y and x in range(1, 27):
    z += y
    plt.scatter(x,z)
    plt.show()
1
  • Where does plt come from? Commented Mar 26, 2020 at 0:34

2 Answers 2

3

has a nice cumulative sum method. Try the following:

import numpy as np

'''
...initial data...

'''

plt.scatter(X,Y, label = 'X vs Y')
cumulative_sum = np.cumsum(Y)

plt.scatter(X,cumulative_sum, label = 'X vs Cumulative Sum')
plt.legend()
plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

@BarryO'Keeffe You should mark the answer correct and upvote it if it worked for you
0

One thing you have wrong is I'm pretty sure you can't loop through two arrays at the same time for y in Y and x in range(1, 27):

You have to loop through one, you can do this by looping through the indices of the array instead of looping through the array itself.

for y in range(0,26):
    x = y + 1
    z += Y[y]
    ...

Another problem you're having, is that you're actually creating a new graph for each time the code in your for loop exectues, each of these graphs only has one point it. These are two of the graphs produced when your for loop starts working correctly, notice how the values at the x and y axis change.

enter image description here enter image description here

You need to save each z value to another array and then print a single graph using that array after your for loop has finished (The for loop will change a bit, because you don't need both y and x)

import numpy as np
import matplotlib.pyplot as plt

a = np.array([[1,1],[2,0],[3,0],[4,1],[5,4],[6,7],[7,5],[8,1],[9,2],[10,3],
[11,10],[12,9],[13,27],[14,20],[15,39],[16,40],[17,54],[18,69],[19,74],
[20,191],[21,126],[22,102],[23,121],[24,219],[25,204], [26,235]])

X = a[:,0]
Y = a[:,1]

plt.scatter(X,Y)
plt.show()


#""""""""""""""""""""""""THE CHANGED PART"""""""""""""""""""""""""""""""""""


Z = np.zeros(26)
sum = 0
for y in range(0, 26):
    sum += Y\[y\]
    Z\[y\] = sum
plt.scatter(X,Z)
plt.show()][3]][3]


#""""""""""""""""""""""""THE CHANGED PART"""""""""""""""""""""""""""""""""""

Produces the graph below

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.