# What do the dots mean in Python

## `matplotlib` - a plotter for diagrams¶

Matplotlib diagrams generally have the following structure:

The basis of every diagram is therefore an object (with a possible title), the actual diagram is determined by the value range of the axes (). In particular, a distinction must be made between and: The latter designation only refers to either the - or the -Axis.

Using the sine plot from the last section, the following example shows how the above objects can be used to adapt or improve the appearance of a Matplotlib diagram. [1]

importnumpyasnpimportmatplotlib.pyplotasplt # Create value lists for a sine and cosine function: x = np.linspace (-np.pi, np.pi, 500, endpoint = True) cos_x = np.cos (x) sin_x = np. sin (x) # plot diagram lines: plt.plot (x, cos_x) plt.plot (x, sin_x) # display diagram: plt.show ()

With the above plot instruction you get - without any further settings - the following diagram:

In this way, you can get an idea of ​​a mathematical function with very little effort. The fact that only a minimal amount of code is required is also due to the fact that standard values ​​are predefined for many settings in the Matplotlib functions. If you were to specify all of these values ​​explicitly, the code example above would look like this:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 # Import modulesimportnumpyasnpimportmatplotlib.pyplotasplt # Create value lists for a sine and cosine function: x = np.linspace (-np.pi, np.pi, 500, endpoint = True) cos_x = np.cos (x) sin_x = np.sin (x) # Create a new Matplot Figure object with 8x6 inches and # a resolution of 100 dpi: plt.figure (figsize = (8,6), dpi = 80) # In this figure a 1x1 diagram - Create grid; # The first of this grid is selected as the current diagram: plt.subplot (111) # Cosine function with blue color, continuous line and 1 pixel # Plot line width: plt.plot (x, cos_x, color = "blue ", linewidth = 1.0, linestyle =" - ") # sine function with green color, continuous line and 1 pixel # plot line width: plt.plot (x, sin_x, color =" green ", linewidth = 1.0, linestyle =" - ") # Define limits for the x-axis: plt.xlim (-4.0,4.0) # Define limits for the y-axis: plt.ylim (-1.0,1.0) #" Ticks "(reference points) for the x-axis define: plt.xticks (np.linspace (-4,4,9, endpoint = True)) # "Ticks" (reference points) for y-axis set: plt.yticks (np.linspace (-1,1,5, endpoint = True)) # show diagram: plt.show ()

The output of this code is absolutely identical to the diagram above. However, this “more detailed” code example can be used very well as a starting point for various adaptations.

The original diagram appears at the original size ( Inches) strongly stretched in the vertical direction; in the case of the sine and cosine functions, their range of values ​​is only between and a wider diagram is probably more suitable. To do this, you can replace the line in the code example above with the following line:

# Adjust the size of the plot: plt.figure (figsize = (10.6), dpi = 80)

The lines are also shown in the original diagram with a line width of only printed. If you were to print this diagram with a black-and-white printer, for example (and then possibly copy the printed page), the lines would no longer be easy to see - the lines would also have similar gray values. To improve this, you can replace the lines and in the code example above with the following lines:

# Adjust the color and thickness of the diagram lines: plt.plot (x, cos_x, color = 'blue', linewidth = 2.5, linestyle = '-') plt.plot (x, sin_x, color = 'red', linewidth = 2.5, linestyle = '-')

There is also no value range for the - and -Axis, the matplotlib simply uses the minima and maxima of the values ​​to be displayed as diagram limits (rounded up to the next larger integer value); the diagram line therefore touches the diagram boundaries. If you want a "softer" transition here, i.e. not adjoining diagram lines, a slightly larger range of values ​​can be selected for the diagram limits. To do this, you can replace the lines and in the code example above with the following lines:

# Adapt the value ranges of the axes: plt.xlim (x.min () * 1.1, x.max () * 1.1) plt.ylim (cos_x.min () * 1.1, cos_x.max () * 1.1)

With these adjustments you get the following diagram when you call up:

Adjust "Ticks" (reference points) for the axes:

The usual scaling is used to represent the trigonometric functions -Axis not ideal: For example, you can only read approximately at which points the functions have zeros or maxima. It would be more practical to scale the -Axis based on the number of circles to be determined. To do this, you can replace the line in the code example above with the following line:

# Set five reference points (as multiples of pi) on the x-axis: plt.xticks ([- np.pi, -np.pi / 2,0, np.pi / 2, np.pi])

If you plot the modified diagram, you get on the Axis shows the numerical values, for example instead of . Fortunately, when you call up you can not only define the position of the ticks, but also specify their labeling by specifying a second list, and optionally also use LaTeX formula symbols for this:

# Set five reference points on the x-axis (as multiples of pi) # and label them using LaTeX symbols: plt.xticks ([- np.pi, -np.pi / 2,0, np.pi / 2, np. pi], [r '\$ - \ pi \$', r '\$ - \ pi / 2 \$', r '\$ 0 \$', r '\$ + \ pi / 2 \$', r '\$ + \ pi \$'] ) # Also adjust ticks for the y-axis: plt.yticks ([- 1.0, -0.5,0,0.5,1], [r '\$ - 1 \$', r '\$ - 1/2 \$', r ' ', r' \$ + 1/2 \$ ', r' \$ + 1 \$ '])

This in front of the individual character strings means that they are viewed as, i.e. special characters such as do not have to be provided with an additional character.

In the example above, the labeling of the -Axis adjusted so that the font is identical. When you call up the result you get the following diagram:

Move diagram axes:

The axis object of a chart has one property called; it defines where the axes are to be displayed. By default, the - Axis printed on the left edge of the chart. This has the advantage that you can also use the right edge for the additional plotting of a second curve as a value axis, provided that the value ranges of the two lines differ greatly from one another.

However, if a coordinate system with four quadrants is to be drawn, for example for discussion of curves or geometric tasks, there is sometimes a diagram with a zero point in the middle and two running through it - respectively -Axes more suitable. To do this, the axes must be "shifted" to the center. This can be achieved by removing two of the four (left, right, top, bottom) and moving the other two to the center. To do this, you can insert the following lines in front of the instruction in the code example above:

# Store the axis object of the diagram in a variable: ax = plt.gca () # Make the upper and right axes invisible: ax.spines ['right']. Set_color ('none') ax.spines ['top' ] .set_color ('none') # Place the left diagram axis on the reference point '0' of the x-axis: ax.spines ['left']. set_position (('data', 0)) # The lower diagram axis on the reference point Set '0' of the y-axis: ax.spines ['bottom']. Set_position (('data', 0)) # Set the alignment of the axis labeling: ax.xaxis.set_ticks_position ('bottom') ax.yaxis. set_ticks_position ('left')

The result is the following diagram when you call up:

This form of representation is elegant, but in this case the lettering of the - and -Axis partially covered by the function graph. As a workaround, you can on the one hand change the font size of the axis labeling and on the other hand highlight it with a semi-transparent border. To do this, you can insert the following code in front of the instruction:

# Highlight axis labels with a white transparent background: forlabelinax.get_xticklabels () + ax.get_yticklabels (): label.set_fontsize (16) label.set_bbox (dict (facecolor = 'white', edgecolor = 'None', alpha = 0.65 ))

The result is obtained by calling:

Sine and cosine plot with different positioning of the axes and highlighted axis lettering.

Normally, diagrams are included in the text with a caption ("Caption"); In most cases, a figure number is also inserted so that the diagram can be clearly referenced from the text. If, on the other hand, you create a diagram for a pin board or an overhead slide / projector presentation, a large printed title above the diagram is sometimes useful. One of these can be added to the diagram as follows:

# Add title: plt.title ('Sin and Cosinus', fontsize = 20, color = 'gray')

Here, too, LaTeX code can be used in the title text if necessary.

As a further improvement, it is very useful if the meaning of the individual lines is displayed as a "legend" in a diagram with several lines. To do this, you can also specify a parameter for the individual instructions and then display the legend using:

# Label plots: plt.plot (x, cos_x, color = "blue", linewidth = 2.5, linestyle = "-", label = r '\$ \ cos (x) \$') plt.plot (x, sin_x, color = "red", linewidth = 2.5, linestyle = "-", label = r '\$ \ sin (x) \$') # Show legend: plt.legend (loc = 'upper left', frameon = True)

Additional text elements can be added to the diagram as additional labeling. Special points can also be highlighted with arrows or auxiliary lines.

# Define the point to be highlighted: pos = 2 * np.pi / 3 # Draw a vertical dashed line at the point 'pos' # (from the x-axis to the graph of the cos function): plt.plot ([pos, pos] , [0, np.cos (pos)], color = 'blue', linewidth = 1.5, linestyle = "-") # Mark point (s) on the cos line: # (The x- and y -Values ​​must - as with plot () - be specified as a list) # (with s = 50 the size ('size') is set to 50 pixels) plt.scatter ([pos], [np.cos (pos )], s = 50, marker = 'o', color = 'blue') # Insert your own text: plt.annotate (r '\$ \ sin (\ frac {2 \ pi} {3}) = \ frac {\ sqrt {3}} {2} \$ ', xy = (pos, np.sin (pos)), xycoords =' data ', xytext = (+ 10, + 30), textcoords =' offset points', fontsize = 16 , arrowprops = dict (arrowstyle = "->", connectionstyle = "arc3, ​​rad = .2")) # Draw a vertical dashed line at the position 'pos' # (from the x-axis to the graph of the sin function) : plt.plot ([pos, pos], [0, np.sin (pos)], color = 'red', linewidth = 1.5, linestyle = "-") # point (s) on the sin line with Markers provided: plt.scatter ([pos], [np.sin (pos)], s = 50 , marker = 'o', color = 'red') # Insert your own text: plt.annotate (r '\$ \ cos (\ frac {2 \ pi} {3}) = - \ frac {1} {2} \$ ', xy = (pos, np.cos (pos)), xycoords =' data ', xytext = (- 90, -50), textcoords =' offset points', fontsize = 16, arrowprops = dict (arrowstyle = "- > ", connectionstyle =" arc3, ​​rad = .2 "))

This finally gives the following diagram:

... to be continued ...

Left

Remarks: