pyplot:在轴上添加点投影

2024-09-27 07:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用plot函数绘制一个图形。 但我想通过在轴上绘制投影并在点和轴上放置文本来强调一些“特殊”点

大概是这样的: enter image description here

我试过这个:

import matplotlib.pyplot as plt

[...]
plt.plot(X, Y, label='data')  # draw curve, X and Y are arrays
plt.plot(Xp, Yp, c, duration), marker='o') # draw point @(Xp, Yp), Xp and Yp are scalars
plt.vlines(Xp, min(Y), Yp, linestyles='dashed')
plt.hlines(Yp, min(X), Xp, linestyles='dashed')
plt.grid(True)
plt.show()

但我得到的并不令人满意:

enter image description here

获得我想要的东西的正确方法是什么?
我也考虑过annotate,但它似乎不能满足我的需要。如果我错了,请纠正我


Tags: and函数import图形plot绘制pltmin
3条回答

像这样的东西可能就是你正在寻找的答案https://stackoverflow.com/a/14434334/14920085

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123] #text that you want to print at the points
fig, ax = plt.subplots()
ax.scatter(z, y)
ax.set_ylabel('y')
ax.set_xlabel('x')
for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

您可以将annotateblended transformation一起使用:

import matplotlib.pyplot as plt

plt.plot([1,2], [2,4], label='data')
plt.plot([1.7], [3.4], marker='o')
plt.grid(True)

x,y = 1.7, 3.4
arrowprops={'arrowstyle': '-', 'ls':' '}
plt.annotate(str(x), xy=(x,y), xytext=(x, 0), 
             textcoords=plt.gca().get_xaxis_transform(),
             arrowprops=arrowprops,
             va='top', ha='center')
plt.annotate(str(y), xy=(x,y), xytext=(0, y), 
             textcoords=plt.gca().get_yaxis_transform(),
             arrowprops=arrowprops,
             va='center', ha='right')

enter image description here

这并不完美,因为您可能仍然需要手动调整轴坐标(例如-0.05而不是0),以将标签设置得稍微偏离轴

你需要玩一下xlimylim

对我来说,这很有效:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == "__main__":
    X = np.linspace(-.5, 3, 100)
    Y = 15000 - 10 * (X - 2.2) ** 2
    Xp = X[-10]
    Yp = Y[-10]

    plt.plot(X, Y, label='data')
    plt.plot(Xp, Yp, marker='o')
    plt.vlines(Xp, min(Y), Yp, linestyles='dashed')
    plt.hlines(Yp, min(X), Xp, linestyles='dashed')
    plt.grid(True)
    plt.xlim(min(X), None)
    plt.ylim(min(Y), None)
    plt.show()

enter image description here

相关问题 更多 >

    热门问题