Home > Software engineering >  How to join/plot these points in python/matplotlib
How to join/plot these points in python/matplotlib

Time:09-25

I was trying to figure out how to extract and plot certain values against one another. The code I have is the following:

    x1 = 0.1
    x2 = 1
    x3 = 10
    x4 = 100
    x5 = 1000

    yz1 = return_two_nums(x1)
    yz2 = return_two_nums(x2)
    yz3 = return_two_nums(x3)
    yz4 = return_two_nums(x4)
    yz5 = return_two_nums(x5)

return_two_nums returns a tuple of 2 floats.

What I want to do is make two separate plots: For the first plot x1, x2, x3, x4, x5 (altogether we can call x) on the x-axis vs. all of the first values of the tuples on the y-axis. For the second plot, the exact same thing except I want x plotted against all the second values of the tuples. How can I go about doing this? Any help would be appreciated. Thank you!

CodePudding user response:

Use list comprehension:

import matplotlib.pyplot as plt

plt.figure()
plt.plot([x1,x2,x3,x4,x5],[first for first,second in [yz1,yz2,yz3,yz4,yz5]])

plt.figure()
plt.plot([x1,x2,x3,x4,x5],[second for first,second in [yz1,yz2,yz3,yz4,yz5]])

CodePudding user response:

Another way of plotting values from this specific function could look like this:

import matplotlib.pyplot as plt
import numpy as np

#exaplary function
def return_two_nums(x):
    arr = np.array(x)
    return (4*arr, arr**0.999)

x = [0.1, 1, 10, 100, 1000]

plt.plot(x, return_two_nums(x)[0], label='first value')
plt.plot(x, return_two_nums(x)[1], label='second value')

This way the code will become more compact and easy to read.

  • Related