如何使用 matplotlib 将散点图点与线连接起来
- 2025-04-16 08:56:00
- admin 原创
- 17
问题描述:
我有两个列表:日期和值。我想用 matplotlib 绘制它们。下面创建了我的数据的散点图。
import matplotlib.pyplot as plt
plt.scatter(dates,values)
plt.show()
plt.plot(dates, values)
创建折线图。
但我真正想要的是一个由线连接点的散点图。
类似于 R 中的:
plot(dates, values)
lines(dates, value, type="l")
这给了我一个点的散点图,上面覆盖着一条连接点的线。
我如何在 python 中做到这一点?
解决方案 1:
我认为@Evert 的答案是正确的:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
这几乎与
plt.plot(dates, values, '-o')
plt.show()
您可以按照文档中的说明将其替换-o
为其他合适的格式字符串。您还可以使用和关键字参数来拆分线条和标记样式的选择。linestyle=
`marker=`
解决方案 2:
对于红线和点
plt.plot(dates, values, '.r-')
或用于 x 标记和蓝线
plt.plot(dates, values, 'xb-')
解决方案 3:
除了其他答案中提供的内容之外,关键字“zorder”还允许人们决定不同对象的垂直绘制顺序。例如:
plt.plot(x,y,zorder=1)
plt.scatter(x,y,zorder=2)
将散点符号绘制在线的顶部,同时
plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)
在散点符号上绘制线条。
例如,参见zorder 演示
解决方案 4:
它们的关键字参数是marker
,你可以使用设置标记的大小markersize
。要生成顶部带有散点符号的线:
plt.plot(x, y, marker = '.', markersize = 10)
要绘制填充点,可以使用标记'.'
或'o'
(小写字母 oh)。所有标记的列表,请参阅:
https://matplotlib.org/stable/api/markers_api.html
解决方案 5:
从逻辑上讲,用线连接散点图点与用标记标记线图上的特定点相同,因此您可以直接使用plot
(本页面其他地方提到过)。您可以在同一个调用中设置标记的面色、边色和大小以及线型、颜色和宽度plot()
。
import matplotlib.pyplot as plt
x = list(range(7))
y = [9, 5, 2, 4, 6, 7, 1]
plt.plot(x, y, marker='^', mfc='r', mec='r', ms=6, ls='--', c='b', lw=2)
话虽如此,使用scatter
+与在上面的调用plot
中定义标记略有不同,因为它会创建一个集合列表(指向散点)。您可以使用and进行检查。因此,如果您必须在绘制图形后更改标记属性,则必须通过while with访问它,所有内容都存储在 中。plot
`scatterax.lines
ax.collections.collections
plot`ax.lines
import random
plt.plot(x, y, '--b')
plt.scatter(x, y, s=36, c='r', marker='^', zorder=2)
plt.gca().lines # <Axes.ArtistList of 1 lines>
plt.gca().collections # <Axes.ArtistList of 1 collections>
plt.plot(x, y, marker='^', mfc='r', mec='r', ms=6, ls='--', c='b')
plt.gca().lines # <Axes.ArtistList of 1 lines>
plt.gca().collections # <Axes.ArtistList of 0 collections>
我发现一个相当重要的直接后果是,scatter
+plot
语法比单纯使用 消耗更多的内存plot()
。如果您在循环中创建多个图形,这一点就变得尤为重要。以下内存分析示例显示,plot
使用标记的 消耗的内存块峰值大小减少了 3 倍以上(在 Python 3.12.0 和 matplotlib 3.8.0 上测试)。
# .profiling.py
import tracemalloc
import random
import matplotlib.pyplot as plt
def plot_markers(x, y, ax):
ax.plot(x, y, marker='^', mfc='r', mec='r', ms=6, ls='--', c='b')
def scatter_plot(x, y, ax):
ax.plot(x, y, '--b')
ax.scatter(x, y, s=36, c='r', marker='^', zorder=2)
if __name__ == '__main__':
x = list(range(10000))
y = [random.random() for _ in range(10000)]
for func in (plot_markers, scatter_plot):
fig, ax = plt.subplots()
tracemalloc.start()
func(x, y, ax)
size, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
plt.close(fig)
print(f"{func.__name__}: size={size/1024:.2f}KB, peak={peak/1024:.2f}KB.")
> py .profiling.py
plot_markers: size=445.83KB, peak=534.86KB.
scatter_plot: size=636.88KB, peak=1914.20KB.
扫码咨询,免费领取项目管理大礼包!