Issue
I'm trying to do a plot with a bunch of data, and I want some of the data, which has NaNs, to be plotted too. The problem I face is that I want a line through the NaN values connecting the other values. If we look at the image, the blue dots should be connected like the orange ones. If there were no NaNs I could draw it, but then I wouldnt be able to draw the orange points, and I need both.
I'll leave the code for the MWE that gives the figure here:
import numpy as np
import matplotlib.pyplot as plt
x = [1.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0]
y= [1.0, 3.0, 5.0, 7.0, 10.0, 5.0, 20.0]
Arealval = [30.1, np.nan, 33.4, np.nan, 22.4, np.nan, 35.8]
plt.plot(x, Arealval, marker= 'X', ls=':')
plt.plot(x, y, marker='o', ls=':')
plt.show()
I thought of duplicating my x values having 2 lists and keeping only the ones without NaN on one of them for the plot, and it works (example and image below) but that would be completely impractical to do with a large dataset.
import numpy as np
import matplotlib.pyplot as plt
x = [1.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0]
y= [1.0, 3.0, 5.0, 7.0, 10.0, 5.0, 20.0]
x2 = [1.0, 5.0, 10.0, 20.0]
Arealval = [30.1, 33.4, 22.4, 35.8]
plt.plot(x2, Arealval, marker= 'X', ls=':')
plt.plot(x, y, marker='o', ls=':')
plt.show()
To be clear, I don't want to interpolate or anything, there are just a bunch of observations (the ones with NaNs), and a bunch of predictions (the ones without NaNs), and I want to plot both, but giving more importance to the observations by having the line to locate them easier.
Is there any way to programatically draw a line between points ignoring the NaNs?
Solution
One option might be to convert to numpy array, then remove the NaNs from Arealval
together with their corresponding x values.
x = np.array(x)
Arealval = np.array(Arealval)
plt.plot(x[~np.isnan(Arealval)],
Arealval[~np.isnan(Arealval)],
marker= 'X', ls=':')
plt.plot(x, y, marker='o', ls=':')
Output:
Answered By - BigBen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.