Programing

matplotlib를 사용하여 수평선 그리기

lottogame 2020. 8. 27. 08:06
반응형

matplotlib를 사용하여 수평선 그리기


스플라인 보간을 사용하여 시계열을 부드럽게했으며 플롯에 수평선을 추가하고 싶습니다. 하지만 제 손에서 벗어난 문제가있는 것 같습니다. 어떤 도움이라도 정말 도움이 될 것입니다. 내가 가진 것은 다음과 같습니다.

annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')

plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()

문제는 [0,len(xs)]수평선 플로팅에 사용하는 것 같습니다 .


당신 [0,len(xs)]말이 맞아요 . 원래 x 축 변수를 재사용하고 변수 xs가있는 동일한 길이의 다른 numpy 배열로 플로팅 할 수 있습니다.

annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')

#####horizontal line
horiz_line_data = np.array([40 for i in xrange(len(xs))])
plt.plot(xs, horiz_line_data, 'r--') 
###########plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()

문제가 해결되기를 바랍니다.


axhline (수평 축선)을 찾고 있습니다. 예를 들어 다음은 y = 0.5에서 수평선을 제공합니다.

import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

샘플 그림


If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y postion and xmin and xmax in the data coordinate(i.e, your actual data range in the x axis). A sample code snippet is:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 21, 200)
y = np.exp(-x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')

plt.show()

The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:

여기에 이미지 설명 입력


In addition to the most upvoted answer here, one can also chain axhline after calling plot on a pandas's DataFrame.

import pandas as pd

(pd.DataFrame([1, 2, 3])
   .plot(kind='bar', color='orange')
   .axhline(y=1.5));

여기에 이미지 설명 입력


A nice and easy way for those people who always forget the command axhline is the following

plt.plot(x, [y]*len(x))

In your case xs = x and y = 40. If len(x) is large, then this becomes inefficient and you should really use axhline.


plt.grid수평선을 그리는 데 사용할 수 있습니다 .

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator

# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)

# plot your data
plt.plot(xs,spl(xs),'b')

# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')

# show
plt.show()

랜덤 데이터 그림 예제

참고 URL : https://stackoverflow.com/questions/33382619/plot-a-horizontal-line-using-matplotlib

반응형