Matplotlib connect scatterplot points with line - Python

PythonMatplotlib

Python Problem Overview


I have two lists, dates and values. I want to plot them using matplotlib. The following creates a scatter plot of my data.

import matplotlib.pyplot as plt

plt.scatter(dates,values)
plt.show()

plt.plot(dates, values) creates a line graph.

But what I really want is a scatterplot where the points are connected by a line.

Similar to in R:

plot(dates, values)
lines(dates, value, type="l")

, which gives me a scatterplot of points overlaid with a line connecting the points.

How do I do this in python?

Python Solutions


Solution 1 - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

You can replace -o with another suitable format string as described in the documentation. You can also split the choices of line and marker styles using the linestyle= and marker= keyword arguments.

Solution 2 - Python

For red lines an points

plt.plot(dates, values, '.r-') 

or for x markers and blue lines

plt.plot(dates, values, 'xb-')

Solution 3 - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

Solution 4 - Python

They keyword argument for this is marker, and you can set the size of the marker with markersize. To generate a line with scatter symbols on top:

plt.plot(x, y, marker = '.', markersize = 10)

To plot a filled spot, you can use marker '.' or 'o' (the lower case letter oh). For a list of all markers, see:
https://matplotlib.org/stable/api/markers_api.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbrno792View Question on Stackoverflow
Solution 1 - PythonHannes OvrénView Answer on Stackoverflow
Solution 2 - PythonSteve BarnesView Answer on Stackoverflow
Solution 3 - PythonUse MeView Answer on Stackoverflow
Solution 4 - PythonericView Answer on Stackoverflow