Matplotlib用线连接散点图-Python

问题:Matplotlib用线连接散点图-Python

我有两个列表,日期和值。我想使用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中执行此操作?

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?


回答 0

我认为@Evert有正确的答案:

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

几乎与

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

或您喜欢的任何线型

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()

or whatever linestyle you prefer.


回答 1

红线表示点

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

或用于x标记和蓝线

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

For red lines an points

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

or for x markers and blue lines

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

回答 2

除了其他答案中提供的内容外,关键字“ 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演示

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