英文:
plot coordinates line in a pyplot
问题
我有一个散点图。我想要为每个点绘制坐标线,从X到Y,就像我们在学校时常做的那样。
请参考下面的图片。
我最终使用了"grid()"属性,但那不完全是我想要的。
我还尝试了使用"axhline"和"axvline",传入xmin、xmax和ymin、ymax,但没有成功。它穿过整个图。
祝你有个美好的一天!
英文:
I have a scatter plot. I would like to plot coordinate lines for each point, from X to Y, just like we used to do on school.
See picture below as a reference.
I ended up using the "grid()" property, but that is not exactly what I want.
I also tried to use "axhline" and "axvline" passing xmin, xmax and ymin, ymax, but it did not work. It crossed a line throughout the entire plot.
Have a great day!
答案1
得分: 2
你可以使用vlines
来绘制垂直线,使用hlines
来绘制水平线。与axvline
和axhline
不同的是,这些函数接受在0到1之间的值,而vlines
和hlines
在数据坐标中工作。我将y.min()
作为ymin
传递给vlines
,以防它太低,将x.min()
作为xmin
传递给hlines
,以防它太靠左。我还调整了散点图的zorder
,使线在点的后面。
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
rng = np.random.default_rng(42)
x = np.arange(2009, 2024)
y = rng.random(x.size)*13
fig, ax = plt.subplots()
ax.scatter(x, y, zorder=3)
ax.vlines(x, y.min(), y, color="r", linewidth=0.5)
ax.hlines(y, x.min(), x, color="r", linewidth=0.5)
fig.show()
英文:
You can use vlines
to draw the vertical lines and hlines
to draw the horizontal lines. These are different from axvline
and axhline
, since those functions take values between 0 and 1 while vlines
and hlines
work in the data coordinates. I pass vlines
the y.min()
as ymin
so it doesn't go too low and I pass hlines
the x.min()
as xmin
so it doesn't go too far to the left. I also adjusted the zorder
of the scatter plot so the lines are behind the points.
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
rng = np.random.default_rng(42)
x = np.arange(2009, 2024)
y = rng.random(x.size)*13
fig, ax = plt.subplots()
ax.scatter(x, y, zorder=3)
ax.vlines(x, y.min(), y, color="r", linewidth=0.5)
ax.hlines(y, x.min(), x, color="r", linewidth=0.5)
fig.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论