- matplotlib.pyplot.plot#
- Matplotlib Markers
- Example
- Result:
- Example
- Result:
- Marker Reference
- Format Strings fmt
- Example
- Result:
- Line Reference
- Color Reference
- Marker Size
- Example
- Result:
- Marker Color
- Example
- Result:
- Example
- Result:
- Example
- Result:
- Example
- Result:
- Example
- Set Marker Size in Matplotlib Scatterplots
- Loading a Sample Matplotlib Scatterplot
- Changing the Marker Size for All Points in Matplotlib Scatterplots
- Changing the Marker Size for Individual Points in Matplotlib Scatterplots Based on Other Data
- Define a Function to Define Marker Sizes in Matplotlib
- What is the Marker Size in Matplotlib?
- Conclusion
- Additional Resources
matplotlib.pyplot.plot#
The coordinates of the points or line nodes are given by x, y.
The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It’s a shortcut string notation described in the Notes section below.
>>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, 'bo') # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, 'r+') # ditto, but with red plusses
You can use Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:
>>> plot(x, y, 'go--', linewidth=2, markersize=12) >>> plot(x, y, color='green', marker='o', linestyle='dashed', . linewidth=2, markersize=12)
When conflicting with fmt, keyword arguments take precedence.
Plotting labelled data
There’s a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj[‘y’] ). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:
>>> plot('xlabel', 'ylabel', data=obj)
All indexable objects are supported. This could e.g. be a dict , a pandas.DataFrame or a structured numpy array.
Plotting multiple sets of data
There are various ways to plot multiple sets of data.
- The most straight forward way is just to call plot multiple times. Example:
>>> plot(x1, y1, 'bo') >>> plot(x2, y2, 'go')
>>> x = [1, 2, 3] >>> y = np.array([[1, 2], [3, 4], [5, 6]]) >>> plot(x, y)
>>> for col in range(y.shape[1]): . plot(x, y[:, col])
By default, each line is assigned a different style specified by a ‘style cycle’. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) ).
Parameters : x, y array-like or scalar
The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)) .
Commonly, these parameters are 1D arrays.
They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).
These arguments cannot be passed as keywords.
fmt str, optional
A format string, e.g. ‘ro’ for red circles. See the Notes section for a full description of the format strings.
Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.
This argument cannot be passed as keyword.
data indexable object, optional
An object with labelled data. If given, provide the label names to plot in x and y.
Technically there’s a slight ambiguity in calls where the second label is a valid fmt. plot(‘n’, ‘o’, data=obj) could be plt(x, y) or plt(y, fmt) . In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot(‘n’, ‘o’, », data=obj) .
A list of lines representing the plotted data.
Other Parameters : scalex, scaley bool, default: True
These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view .
**kwargs Line2D properties, optional
kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:
>>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.
Here is a list of available Line2D properties:
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image
Matplotlib Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
Example
Mark each point with a circle:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, marker = ‘o’)
plt.show()
Result:
Example
Mark each point with a star:
Result:
Marker Reference
You can choose any of these markers:
Marker | Description | |
---|---|---|
‘o’ | Circle | Try it » |
‘*’ | Star | Try it » |
‘.’ | Point | Try it » |
‘,’ | Pixel | Try it » |
‘x’ | X | Try it » |
‘X’ | X (filled) | Try it » |
‘+’ | Plus | Try it » |
‘P’ | Plus (filled) | Try it » |
‘s’ | Square | Try it » |
‘D’ | Diamond | Try it » |
‘d’ | Diamond (thin) | Try it » |
‘p’ | Pentagon | Try it » |
‘H’ | Hexagon | Try it » |
‘h’ | Hexagon | Try it » |
‘v’ | Triangle Down | Try it » |
‘^’ | Triangle Up | Try it » |
‘ | Triangle Left | Try it » |
‘>’ | Triangle Right | Try it » |
‘1’ | Tri Down | Try it » |
‘2’ | Tri Up | Try it » |
‘3’ | Tri Left | Try it » |
‘4’ | Tri Right | Try it » |
‘|’ | Vline | Try it » |
‘_’ | Hline | Try it » |
Format Strings fmt
You can also use the shortcut string notation parameter to specify the marker.
This parameter is also called fmt , and is written with this syntax:
Example
Mark each point with a circle:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, ‘o:r’)
plt.show()
Result:
The marker value can be anything from the Marker Reference above.
The line value can be one of the following:
Line Reference
Note: If you leave out the line value in the fmt parameter, no line will be plotted.
The short color value can be one of the following:
Color Reference
Color Syntax | Description | |
---|---|---|
‘r’ | Red | Try it » |
‘g’ | Green | Try it » |
‘b’ | Blue | Try it » |
‘c’ | Cyan | Try it » |
‘m’ | Magenta | Try it » |
‘y’ | Yellow | Try it » |
‘k’ | Black | Try it » |
‘w’ | White | Try it » |
Marker Size
You can use the keyword argument markersize or the shorter version, ms to set the size of the markers:
Example
Set the size of the markers to 20:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, marker = ‘o’, ms = 20)
plt.show()
Result:
Marker Color
You can use the keyword argument markeredgecolor or the shorter mec to set the color of the edge of the markers:
Example
Set the EDGE color to red:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, marker = ‘o’, ms = 20, mec = ‘r’)
plt.show()
Result:
You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge of the markers:
Example
Set the FACE color to red:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, marker = ‘o’, ms = 20, mfc = ‘r’)
plt.show()
Result:
Use both the mec and mfc arguments to color the entire marker:
Example
Set the color of both the edge and the face to red:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, marker = ‘o’, ms = 20, mec = ‘r’, mfc = ‘r’)
plt.show()
Result:
Example
Mark each point with a beautiful green color:
Result:
Example
Mark each point with the color named «hotpink»:
Set Marker Size in Matplotlib Scatterplots
In this tutorial, you’ll learn how to define and set the marker size in Matplotlib scatterplots. Being able to control the size of your Matplotlib scatterplots allows you to add extra information to your scatterplots.
This allows you to communicate more details about your data and make it clearer to your visualization’s readers. Matplotlib allows you to customize the size for all plots as well as for individual plots, based on other data criteria.
By the end of this tutorial, you’ll have learned:
- How to set the marker size for all points in a Matplotlib scatterplot
- How to set the marker size for points in a Matplotlib scatterplot based on other data
- Develop a function to define marker size in Matplotlib
Loading a Sample Matplotlib Scatterplot
In order to follow along with this tutorial, feel free to load the plot below. The code loads both x and y coordinates for a scatterplot. Additionally, we set the x and y limits of the plot and give the plot a title to better understand what is going on.
# Loading a sample scatter plot import matplotlib.pyplot as plt plt.style.use('seaborn') x = [1,2,3,4,5,6,7,8,9] y = [2,4,6,7,4,3,2,4,6] plt.scatter(x, y) plt.xlim(0, 10) plt.ylim(0, 10) plt.title('A Sample Scatter Plot - datagy.io') plt.show()
This returns the following image:
In the next section, you’ll learn how to change the marker size for all points in a Matplotlib scatterplot.
Changing the Marker Size for All Points in Matplotlib Scatterplots
Matplotlib makes it simple to change the plot size for all points in a scatter plot. The size of points is based on the s= parameter. The parameter accepts either an integer or a list of values. These options determine what the size of the markers is:
- Passing in a single value changes the size for all markers
- Passing in a list of values changes the size for each marker individually
Let’s see how we can change the size for all markers using the s= parameter:
# Changing the size for all markers in Matplotlib import matplotlib.pyplot as plt plt.style.use('seaborn') x = [1,2,3,4,5,6,7,8,9] y = [2,4,6,7,4,3,2,4,6] # Using s= to change the marker size plt.scatter(x, y, s=100) plt.xlim(0, 10) plt.ylim(0, 10) plt.title('Changing Marker Sizes for All Points - datagy.io') plt.show()
This returns the following image:
To understand what the s= parameter controls, we need to take a look at the documentation. The s parameter is defined as the marker size in points ** 2, meaning that the value passed in is squared. In order to get a marker that is, say, size 10, we need to pass in the square of that.
Changing the Marker Size for Individual Points in Matplotlib Scatterplots Based on Other Data
In this section, we’ll look at using another set of values to set the size of matplotlib scatterplot markers. Let’s say we had another dimension to our data, we can use the values in that dimension to control the size. Because the s= parameter also accepts an array of values, we can simply pass in that array.
Let’s see what this might look like. We’ll add another array of values that will control the size:
# Controlling the size of markers with another variable import matplotlib.pyplot as plt plt.style.use('seaborn') x = [1,2,3,4,5,6,7,8,9] y = [2,4,6,7,4,3,2,4,6] # Adding another variable to control size z = [10,20,10,15,100,25,50,70,80] plt.scatter(x, y, s=z) plt.xlim(0, 10) plt.ylim(0, 10) plt.title('Changing Marker Sizes Based on Another Value - datagy.io') plt.show()
This returns the following image:
This can be a very helpful method when we’re attempting to control the size of a marker based on a DataFrame column.
Define a Function to Define Marker Sizes in Matplotlib
Following the logic of the example above, we can define a function that uses either the x or y parameters to define the size of markers in a Matplotlib scatterplot. The example below is just that – an example. You can define the function however you like.
In the code below, the size of the marker is relative to the value of x , increasing it by a factor of 3:
# Using a function to define marker size import matplotlib.pyplot as plt plt.style.use('seaborn') x = [1,2,3,4,5,6,7,8,9] y = [2,4,6,7,4,3,2,4,6] def set_marker_size(x, factor): return [x_i**factor for x_i in x] plt.scatter(x, y, s=set_marker_size(x,3)) plt.xlim(0, 10) plt.ylim(0, 10) plt.title('Changing Marker Sizes Using a Function - datagy.io') plt.show()
This returns the following image:
What is the Marker Size in Matplotlib?
Understanding what the marker size represents simplifies a lot of the understanding behind it. It may feel like we’ve been setting values arbitrarily. However, as with everything else in Matplotlib there is significant logic behind it.
Each point is actually the pixel size, which varies by the resolution that you set for the figure itself. By default, Matplotlib uses a resulting of 100 DPI (meaning, per inch). If you were to change this, then the relative sizes that you see would change as well.
Conclusion
In this tutorial, you learned how to set the marker size of scatterplot points in Matplotlib. Being able to modify the size of markers allows you to more effectively communicate the intent of your data. You first learned how to change the size of all markers. Then, you learned how to change the size of markers based on another value. This allows you to add another dimension to your data.
Additional Resources
To learn more about related topics, check out the tutorials below: