Amnesia Smith
Amnesia Smith

Reputation: 27

Plotting graphs with empty elements in a list

import matplotlib.pyplot as plt

x = [2.4, 3.2, 4.435, 5.65, 6.4, 7.333, 8.5, 9.2345]
y = [1.4356, "", 5.32245, 6.542, 7.567, .77558, "", ""]

y1 = [] 
for string in (y):
    if (string != ""):
        y1.append(string)

plt.plot(x, y1, 'b.', label="Sample data")
plt.show()

When I try to plot this I get Value Error "x and y must have same first dimension, but have shapes (8,) and (5,)"

I want to skip over these empty elements and plot just the 5 points but I don't know how to go about it.

Upvotes: 1

Views: 2012

Answers (2)

Beny Gj
Beny Gj

Reputation: 615

here you can use with numpy to put NAN instead of quote

#!/user/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np

x = [2.4, 3.2, 4.435, 5.65, 6.4, 7.333, 8.5, 9.2345]
y = [1.4356, "", 5.32245, 6.542, 7.567, .77558, "", ""]

y1 = []
for string in (y):
    if string != "":
        string = np.NAN
    y1.append(string)


if __name__ == '__main__':

    plt.plot(x, y1, 'b.', label="Sample data")
    plt.show()

Upvotes: 1

Otto Hanski
Otto Hanski

Reputation: 394

The plot command wants the x and y dimension arrays you give it to be the same size. But since y1 is simply y with some elements removed, the y1 list will have fewer elements than the list of x coordinates. An easy workaround is to simply create also an x1 list, where you add the x coordinates matching the y1 coordinates, and plotting using x1 and y1.

Here's an example solution:

import matplotlib.pyplot as plt

x = [2.4, 3.2, 4.435, 5.65, 6.4, 7.333, 8.5, 9.2345]
y = [1.4356, "", 5.32245, 6.542, 7.567, .77558, "", ""]

x1 = []
y1 = [] 
for index in range(len(y)):
    if (y[index] != ""):
        y1.append(y[index])
        x1.append(x[index])

plt.plot(x1, y1, 'b.', label="Sample data")
plt.show()

Note that the loop was changed to loop by index, rather than the value of items in the list, since this lets us easily take the matching pairs of values from both lists.

Upvotes: 2

Related Questions