Marking y value using dotted line in matplotlib.pyplot

时间:2018-06-18 11:37:46

标签: python matplotlib

I am trying to plot a graph using matplotlib.pyplot.

import matplotlib.pyplot as plt
import numpy as np

x = [i for i in range (1,201)]
y = np.loadtxt('final_fscore.txt', dtype=np.float128)
plt.plot(x, y, lw=2)
plt.show()

It looks something like this: What i have done so far

I want to mark the first value of x where y has reached the highest ( which is already known, say for x= 23, y= y[23]), like this figure shown below:

What I want to do

I have been searching this for some time now, with little success. I have tried adding a straight line for now, which is not behaving the desired way:

import matplotlib.pyplot as plt
import numpy as np

x = [i for i in range (1,201)]
y = np.loadtxt('final_fscore.txt', dtype=np.float128)

plt.plot(x, y, lw=2)

plt.plot([23,y[23]], [23,0])

plt.show()

Resulting graph:

Not what I want

Note: I want to make the figure like in the second graph.

1 个答案:

答案 0 :(得分:3)

目前尚不清楚y[23]会在这做什么。您需要找出最大值和发生这种情况的索引(np.argmax)。然后,您可以使用它来绘制带有这些坐标的3点线。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(9)

x = np.arange(200)
y = np.cumsum(np.random.randn(200))
plt.plot(x, y, lw=2)

amax = np.argmax(y)
xlim,ylim = plt.xlim(), plt.ylim()
plt.plot([x[amax], x[amax], xlim[0]], [xlim[0], y[amax], y[amax]],
          linestyle="--")
plt.xlim(xlim)
plt.ylim(ylim)

plt.show()

enter image description here