Customizing Grid
Another important part of the customization is grid customization. pyplot
module has a grid()
function for this purpose.
Visibility and Axes
Its first parameter visible
specifies whether to show the grid lines (by default, they are not shown).
The axis
parameter in grid customization allows you to control the direction in which grid lines appear on a plot:
'x'
β displays vertical grid lines aligned with the x-axis;'y'
β displays horizontal grid lines aligned with the y-axis;'both'
β displays grid lines in both directions (this is the default behavior).
This parameter is useful when you want to emphasize data alignment along a specific axis or reduce visual clutter by limiting grid lines to one direction.
import matplotlib.pyplot as plt import numpy as np data_linear = np.arange(0, 11) data_squared = data_linear ** 2 plt.plot(data_linear, label='linear function', color='red', alpha=0.5) plt.plot(data_squared, '-o', label='quadratic function', color='blue') plt.xticks(data_linear) plt.xlabel('x', loc='right') plt.ylabel('y', loc='top', rotation=0) # Setting the horizontal grid lines to be visible plt.grid(True, axis='x') plt.legend() plt.show()
In this example, visible=True
and axis='x'
were set to enable only the vertical grid lines. This enhances the plot by adding useful reference lines while avoiding unnecessary horizontal elements.
Color and Transparency
It is also possible to change the color of the grid lines using the color
parameter and their transparency using the alpha
parameter.
import matplotlib.pyplot as plt import numpy as np data_linear = np.arange(0, 11) data_squared = data_linear ** 2 plt.plot(data_linear, label='linear function', color='red', alpha=0.5) plt.plot(data_squared, '-o', label='quadratic function', color='blue') plt.xticks(data_linear) plt.xlabel('x', loc='right') plt.ylabel('y', loc='top', rotation=0) # Customizing the horizontal grid lines plt.grid(True, axis='x', alpha=0.2, color='black') plt.legend() plt.show()
Now our grid lines are black (color='black'
) and are more transparent (alpha=0.2
) which makes the plot look even better.
There are still more possible parameters for the grid()
functions (they are not used so often), so here is its grid()
documentation in case you want to explore more.
Swipe to start coding
Customize the grid lines on the plot by completing the function call:
- Use the correct function to configure grid lines.
- Make the grid visible by setting the first argument appropriately.
- Restrict the grid to lines parallel to the x-axis by setting the
axis
parameter. - Set the grid line color to
'slategrey'
using thecolor
parameter. - Adjust the transparency of the grid lines to
0.5
using thealpha
parameter.
Solution
Thanks for your feedback!