Ignoring None as one of the values

Question:

I need to plot two sets of data on the same chart with error bars. But I don’t have one of the measurements.

days = [0.43, 1.72, 3.97, 4.81, 9.54, 10.9]
magB = [None, 3.36, 3.9, 4.27, 5.47, 5.59]
magV = [10.8, 2.88, 3.59, 3.89, 5.57, 5.82]

fix, ax = plt.subplots()
plt.xlabel("days")
plt.ylabel("mag")
plt.yticks(np.arange(3, 6, 0.5))
plt.scatter(days, magB, label='magB')
plt.scatter(days, magV, label='magV')
plt.errorbar(days, magB, yerr=1, fmt="o")
plt.errorbar(days, magV, xerr=1, fmt="o")
plt.legend()
ax.invert_yaxis()
plt.show()

But it returns the error when calculating the error:

  File "test.py", line 26, in <module>
    plt.errorbar(days, magB, yerr=0.1, fmt="o")
  File "matplotlib/pyplot.py", line 2537, in errorbar
    return gca().errorbar(
  File "matplotlib/__init__.py", line 1442, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "matplotlib/axes/_axes.py", line 3648, in errorbar
    low, high = dep + np.row_stack([-(1 - lolims), 1 - uplims]) * err
TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'

Process finished with exit code 1

I understand it cannot apply the error to the None value. What can I do about it?

I cannot simply ignore the first days value as it will be needed further (more data to plot on the same chart)

Asked By: Malvinka

||

Answers:

There is obviously no meaningful error or value for the first day magB so can’t you just use:

plt.scatter(days[1:], magB[1:], label='magB')
plt.errorbar(days[1:], magB[1:], yerr=1, fmt="o")

and leave the others as they are. The plot then works OK looks fine to me,

Answered By: user19077881

You can replace None with np.nan, then the missing data will be ignored by the plot.

Answered By: Jan Kuiken
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.