minecraftplayer1234
minecraftplayer1234

Reputation: 2227

Matplotlib plot a graph with changing formula

So I basically have some data which is like this: x = [0, 5, 12, 17] and y = [0, 1, 0, 0] (I mean those are really long lists). Now I would like to plot a graph which has value of 0 from 0 to 5, then from 5 to 12 -> 1, and then from 12 to 17 the value of 0. Now I can do this by generating an arrays like this: x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] and y = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, ...., 0] and just plt.plot(x,y). But for large arrays this is not efficient I guess, so I would like to ask if there is a matplotlib method to print specified value or function formula within a specified range? (like sin(x) from 0 to 5 and something else further)

Upvotes: 0

Views: 58

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

Plotting the example data can be done using plt.step. In this case, the argument where must be where="post".

import matplotlib.pyplot as plt

x = [0, 5, 12, 17]
y = [0, 1, 0, 0]

plt.step(x, y, where='post', label='step')
plt.xticks(x)

plt.show()

enter image description here

Upvotes: 1

Related Questions