# Cave of Python

»»» Line Plots

## Line Plots

To create a 2D plot consisting of points joined by lines, use the plot function.

We can supply x- and y-axis data as the first two arguments of this function.

``````import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 20, 0.1)
y = np.sin(x)

plt.plot(x, y)
plt.show()``````

The third argument to plot can be a string that specifies what to display.

• – means display solid lines connecting samples
• – – means display dashed lines
• o means display markers for the samples

The size of the markers, if used, is controlled by the markersize parameter.

The color of the line is controlled by the color parameter.

``````import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 20, 0.1)
y = np.sin(x)

plt.plot(x, y, '--o', markersize=4, color='red')
plt.show()``````

#### Labels, Titles and Legends

To set the title of the whole graph, use the title method.

You can set x- and y-axis titles using xlabel and ylabel.

You can easily add more lines to the same chart. In this case it’s convenient to give the separate graphs legends using the label parameter, and to turn on legend display with the legend method.

``````import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

# Set the overall title
plt.title("Trig Functions")

# Set the y-axis label
plt.xlabel("x")
plt.ylabel("Trig function value")

plt.plot(x, y1, '-o', markersize=4, color='red', label="sin(x)")
plt.plot(x, y2, '-o', markersize=4, color='green', label="cos(x)")

# Turn on display of the labels
plt.legend()
plt.show()``````

Blog at WordPress.com.