在pyplot中绘制坐标线。

huangapple go评论64阅读模式
英文:

plot coordinates line in a pyplot

问题

我有一个散点图。我想要为每个点绘制坐标线,从X到Y,就像我们在学校时常做的那样。

请参考下面的图片。

在pyplot中绘制坐标线。

我最终使用了"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.

在pyplot中绘制坐标线。

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来绘制水平线。与axvlineaxhline不同的是,这些函数接受在0到1之间的值,而vlineshlines在数据坐标中工作。我将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()

在pyplot中绘制坐标线。

英文:

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

在pyplot中绘制坐标线。

huangapple
  • 本文由 发表于 2023年6月29日 22:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定