Two questions related to plotting and the below user defined functions. By way of background, this is the first time I've seen plt.plot
called inside a for loop such that each point is plotted individually. I'm used to seeing entire arrays passed as arguments such as in plt.plot(x, f(x))
. My first question is what is the benefit of iterating over each point and calling plt.plot each time? Is there some additional control over the plot by using this method as opposed to calling plt.plot(x, f(x))
and passing all the points once?
My second question is with regard to the styles parameter in the below function. I’m unsure how or why indexing into a list containing a single character works? styles = [‘b’]
is a list containing a single character. So my expectation is that any slicing/indexing with an argument other than 0, would raise an exception. In other words, I would expect that when the for loop index exceeds 0 (e.g. styles[1], styles [2],
etc.) then an exception would be thrown. What am I missing?
import numpy as np
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
%matplotlib inline
def f(x):
return np.sin(x) + 0.5 * x
def create_plot(x, y, styles, labels, axlabels):
plt.figure(figsize=(10, 6))
for i in range(len(x)):
plt.plot(x[i], y[i], styles[i], label=labels[i])
plt.xlabel(axlabels[0])
plt.ylabel(axlabels[1])
plt.legend(loc=0)
x = np.linspace(-2 * np.pi, 2 * np.pi, 50)
create_plot([x], [f(x)], ['b'], ['f(x)'], ['x', 'f(x)'])