0

Code:

import matplotlib.pyplot as plt
import numpy as np

poslist = []
numlist = []
i = 1

num = int(input('Number to check?'))
plt.title(str(num) + ': Collatz Graph')
plt.xlabel('Step')
plt.ylabel('Value')
print(num)
poslist.append(i)
numlist.append(num)

while True:
    i = i + 1
    if num % 2 == 0:
        num = num // 2
        print(num)
    elif num == 1:
        break
    else:
        num = num * 3
        num = num + 1
        print(num)
        poslist.append(i)
        numlist.append(num)

axislist = np.array((poslist, numlist))
print(axislist)
plt.plot(axislist)
plt.show()

I am trying to turn 2 lists into one Numpy Array. poslist, the first list, will add a number with each step that increments by 1 from the previous. (e.g [1, 2, 3, 4]). The second list, numlist, will append a number each step that corresponds with the Collatz Conjecture. I need to combine these two with the format: ((poslist, numlist)). This will then be input into the matplotlib.plot() function which will convert it to a graph. poslist will show the x-axis on the line graph, and numlist will show the y-axis. However, with the code I have, it does not output a continuous line of the value changing, but it outputs many coloured lines with no discernable origin, except that one starts at 0 and ends at the value that is run through the code on the y-axis, going from 0 to 1 on the x-axis:

graph when input is 100

4
  • 1
    Why not just plt.plot(poslist, numlist)? Commented Nov 5, 2021 at 23:53
  • Yeah that works, I just have to change it to plt.plot(*(poslist, numlist)). Thanks! Commented Nov 6, 2021 at 13:32
  • Well, plt.plot(*(poslist, numlist)) is just the same as plt.plot(poslist, numlist). Why do you want to complicate things so much? Commented Nov 6, 2021 at 13:35
  • honestly, I am very new to this so I wasn’t sure of the best solution. If there is a better way, I’ll use it. Commented Nov 6, 2021 at 14:01

1 Answer 1

1

Do plt.plot(*axislist).

By default, plt.plot parses a single argument as y-coordinates. Hence, in your case each column is used to define a line. You need to pass both x coordinates and y coordinates, which you can do by adding *. In Python, * will split the numpy array into two subarrays defined by its rows.

Sign up to request clarification or add additional context in comments.

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.