Перейти к содержимому

Plt grid python что это

  • автор:

How to Add a Matplotlib Grid on a Figure

a) In this example, we will try to make grids on our strictly increasing plot:

b) Here, we create a strictly increasing graph (the slope will constantly increase).

  • We use a scatter plot to display our data points.
  • The .gca() function is used to get the current polar axes of our plot.
  • We use the .grid() function to represent grids in our plots.
  • Here's the output of the above code:

Note: There are many other ways to add grids to your plots, but this will ensure your code's scalability and readability.

c) Let's talk about a very efficient type of grid, the logarithmic grid

Logarithmic grids help us to analyse data more efficiently, as the spaces in the grid are logarithmic-spaced.

For a logarithmic grid, we must add the which and axis parameters to our grid function.

Syntax:

What is Background Grid in Matplotlib?

  • A background grid in Matplotlib is when we try to superimpose a rectangular grid in the background of a plot.
  • The normal grid consists of straight lines intersecting at specific points. However, regarding background grids, the shape and density of the grid can be varied according to our needs.
  • We can specify parameters if we want our grids to be dotted or have breaks. Output:

How to Customize a Grid in Matplotlib?

  • Customizing grids in matplotlib is one of the most salient features in matplotlib. It has many use cases.
  • Suppose your client wants you to sort women's clothing by red and men's clothing by blue. You would have to create a grid in such a way that it differentiates between red and blue clothes.
  • There are a lot of functions in Matplotlib to customize grids. A few of them are:
  • set_facecolor() where: color: hex-code of any colour.
  • Example****Example: Output:

How to Add a Grid When the Ticks are Off?

  • The values used to display certain positions on the coordinate axis are called ticks. It might be a string or a number.
  • The axes automatically change and take the default ticks whenever we plot a graph.
  • To demonstrate this, we will take the "GDP-2014" dataset.

More Grid Examples

Here are some grid examples that will help you understand the concept and meaning of grids in a better way.

In this example, we will try to create a simple and comprehensive grid for a plot.

Output:

In this example, we will try to render a major and minor grid.

Rendering a major grid on a minor grid means that we would have our smaller/minor grids inside our major grids.

Grid lines in matplotlib

Adding grid lines in matplotlib with the grid function

How to add a grid onto a matplotlib chart?

If you want to display grid lines in your plot you will need to call the grid function from matplotlib after creating a plot.

Grid for the X-axis

The grid lines are added by default both for the X and Y axes, but it is possible to set the grid only for one of them. On the one hand, if you want to add the grid lines for the X axis you can set the axis argument to «x» .

Grid for the Y-axis

On the other hand, if you want to display the grid lines for the Y-axis just set the axis argument to «y» .

Grid lines below points

In the previous examples the grid lines were added over the points. However, it is possible to add the lines behind the points just setting set_axisbelow to True .

Major grid

The grid function provides an argument named which . By setting this argument to «major» all the styling will be applied only to the major grid.

Minor grid

If you set the which argument to «minor» you will be able to customize the settings of the minor grid. Nonetheless, unless you call minorticks_on the minor grid won’t show up.

Minor grid without minor ticks

In the previous example, when using the minorticks_on function, the minor ticks will be displayed along the axes. If you prefer not to show those ticks you can remove them with the following line of code:

Minor and major grid at the same time

Setting which to both will display both the minor and major grid as long as you also call the minorticks_on function. An alternative is to add each grid individually, which will allow you to set different settings for each grid.

Grid style customization

The properties of the grid can be customized through several parameters. Note that you can apply these styling for the whole grid or create several grids (with axis or which ) and apply the desired customizations for each grid.

Grid lines color

The default color of the grid lines can be overriden by setting a new color to the color argument

Grid lines style

The style or type of line used to create the grid can be customized with the linestyle or ls argument. In the following example we are setting a dashed line.

Grid lines width

The width of the grid lines can be customized both for major and minor grid lines. If you use both grids, the most common practice is to set the major grid wider than the minor grid. The linewidth or lw argument can be used for this purpose.

Lines transparency

The alpha argument controls the transparency of the grid lines. This argument is very interesting if you want faded grid lines.

Matplotlib Adding Grid Lines

With Pyplot, you can use the grid() function to add grid lines to the plot.

Example

Add grid lines to the plot:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

Result:

Specify Which Grid Lines to Display

You can use the axis parameter in the grid() function to specify which grid lines to display.

Legal values are: ‘x’, ‘y’, and ‘both’. Default value is ‘both’.

Example

Display only grid lines for the x-axis:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

Result:

Example

Display only grid lines for the y-axis:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

Result:

Set Line Properties for the Grid

You can also set the line properties of the grid, like this: grid(color = ‘color‘, linestyle = ‘linestyle‘, linewidth = number).

Matplotlib Grid

To create a basic plot with a “Matplotlib Grid”, import the “matplotlib” library and create some sample data.

Example: Creating a Scatter Plot With Matplotlib Grid
Let’s create a scatter plot via the following example code:

In the above code, firstly create a scatter plot with “500” random data points. After that, the “plt.grid()” function is used to enable the grid lines in the plot. Note that by default, the grid lines are displayed with a solid, gray color.

Output

In the above output, the grid line has been enabled in the scatter plot via the “plt.grid()” function.

How to Customize the Grid Lines in Python?

“Matplotlib Grid” allows us to customize the grid lines in a plot as well. We can change the “color”, “style”, and “width” of the grid lines. Let’s perform this customization using the below examples:

Example 1: Changing the “Color” of the Matplotlib Grid Lines
The “color” attribute can be applied to change the color of matplotlib grid lines:

In the above code, the “plt.grid()” function assigns the “color” attribute value as “r” which enables the grid line in “red” color to the specified scatter plot.

Output

In the above output snippet, the color of the grid lines has been changed accordingly.

Example 2: Changing the “Style” of the Matplotlib Grid Lines
“Matplotlib Grid” supports various line styles for the grid lines. In order to modify the linestyle of the grid lines, use the “linestyle” argument/attribute. Let’s change the style of the grid lines to “dashed” via the below-stated code:

According to the above code snippet, the “plt.grid()” function assigns the “linestyle” argument as =‘–’ which changes the style of the grid lines in a corresponding manner.

Output

As seen, the style of the grid lines has been changed.

Example 3: Changing the “Width” of the Matplotlib Grid Lines
The width of the grid lines can also be changed using the “linewidth” attribute, as follows:

In the above output, the “plt.grid()” function assigns the “linewidth” attribute as “2”, and the color attribute as “r” to change the line width and color of the grid lines, respectively.

Output

The above snippet shows that the grid line width and color have been changed.

Conclusion

To create and customize grid lines in Python, the “plt.grid()” function of the “Matplotlib” library is used along with various attributes. Also, the grid lines can be customized such as changing the color, style, width, etc. by applying various attributes of the “plt.grid()” function. This Python blog presented an in-depth guide on how to enable the gridlines in any matplotlib plot and customize them using various attributes.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *