Reputation: 1592
Trying to add missing values (None) or in numpy
np.nan
to my matplot graph. Normally it is possible to have missing values in this way:
import matplotlib.pyplot as plt
fig = plt.figure(1)
x = range(10)
y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10]
ax = fig.add_subplot(111)
ax.plot(x, y, 'ro')
plt.show()
But looks like missing values aren't easily supported at the beginning of the graph.
import matplotlib.pyplot as plt
fig = plt.figure(1)
x = range(10)
y = ([None]*5)+[x for x in range(5)]
ax = fig.add_subplot(111)
ax.plot(x, y, 'ro')
plt.show()
This displays:
But I would like to start with x=0
instead of x=5
.
Hope there is a simple method for this problem.
Upvotes: 2
Views: 1895
Reputation: 65430
The reason why the empty values don't seem to have an effect on the second plot is because of the automatic determination of the x and y limits of the axes object. In the first case, you have "real" data that spans the whole x / y range you care about and the axes is automatically scaled to fit this data. In the second example, your real data only covers the upper range of x values so matplotlib will truncate the x axis because there is nothing to show.
The way around this is to explicitly specify the xlims of the axes. You can use your value for x
to determine what these should be.
plt.xlim(x[0], x[-1])
Upvotes: 4
Reputation: 2601
Matplotlib automatically choses the parameters for x- and y- axes. In this case it is only showing the dots that can be visualized. If either x- or y is "None", nothing can be visualized. If you yet want to see the "empty" part of the graph, just adjust the axis range yourself.
How to do so, has been answered multiple times in similiar questions in this forum such as:
Matplotlib/pyplot: How to enforce axis range?
Python, Matplotlib, subplot: How to set the axis range?
setting y-axis limit in matplotlib
and plenty more. Therefore I will refrain from repeating what has been said elsewhere in this forum.
Upvotes: 3