Plot een horizontale lijn met matplotlib

Ik heb spline-interpolatie gebruikt om een tijdreeks glad te strijken en wil ook een horizontale lijn aan de plot toevoegen. Maar er lijkt een probleem te zijn dat ik niet in de hand heb. Om het even welke hulp zou werkelijk nuttig zijn. Dit is wat ik heb:

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

probleem lijkt te zijn met mijn gebruik van [0,len(xs)]voor het plotten van horizontale lijnen.


Antwoord 1, autoriteit 100%

Je hebt gelijk, ik denk dat de [0,len(xs)]je afschrikt. U wilt de originele x-asvariabele xsopnieuw gebruiken en die plotten met een andere numpy-array van dezelfde lengte waarin uw variabele staat.

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

Hopelijk verhelpt dat het probleem!


Antwoord 2, autoriteit 91%

U zoekt naar axhline(een horizontale aslijn). Het volgende geeft u bijvoorbeeld een horizontale lijn op y = 0.5:

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


Antwoord 3, autoriteit 99%

Als je een horizontale lijn in de assen wilt tekenen, kun je ook proberen ax.hlines()methode. U moet de positie yen xminen xmaxopgeven in de gegevenscoördinaat (d.w.z. uw werkelijke gegevensbereik op de x-as). Een voorbeeldcodefragment 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()

Het bovenstaande fragment tekent een horizontale lijn in de assen op y=0.2. De horizontale lijn begint bij x=4en eindigt bij x=20. De gegenereerde afbeelding is:


Antwoord 4, autoriteit 98%

Gebruik matplotlib.pyplot.hlines:

  • Plot meerdere horizontale lijnen door een listdoor te geven aan de parameter y.
  • ykan als één locatie worden doorgegeven: y=40
  • ykan als meerdere locaties worden doorgegeven: y=[39, 40, 41]
  • Als je een figuur plot met iets als fig, ax = plt.subplots(), vervang dan plt.hlinesof plt.axhlinemet respectievelijk ax.hlinesof ax.axhline.
  • matplotlib.pyplot.axhlinekan slechts één locatie plotten (bijv. y=40)
  • Voor verticale lijnen, zie SO: Verticale lijnen tekenen op een gegeven plot in matplotlib

plt.plot

import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

ax.plot

import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))
ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')
ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')
plt.tight_layout()
plt.show()

Tijdreeksas

  • xminen xmaxaccepteren een datum zoals '2020-09-10'of datetime(2020, 9, 10)
    • xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
    • Gegeven date = df.index[9], xmin=date, xmax=date + pd.Timedelta(days=3), waarbij de index een DatetimeIndex.
import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt
# get test data
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]
# plot dataframe
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')
# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')
ax.legend()
plt.show()

  • Voorbeeld van tijdreeksgegevens als web.DataReaderniet werkt.
data = {pd.Timestamp('2020-09-01 00:00:00'): {'High': 3528.03, 'Low': 3494.6}, pd.Timestamp('2020-09-02 00:00:00'): {'High': 3588.11, 'Low': 3535.23}, pd.Timestamp('2020-09-03 00:00:00'): {'High': 3564.85, 'Low': 3427.41}, pd.Timestamp('2020-09-04 00:00:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}
df = pd.DataFrame.from_dict(data, 'index')

Antwoord 5, autoriteit 156%

Naast het meest gewaardeerde antwoord hier, kan men ook axhlinekoppelen na het aanroepen van plotop een pandas‘s DataFrame.

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


Antwoord 6, autoriteit 56%

Een leuke en gemakkelijke manier voor die mensen die altijd het commando axhlinevergeten, is het volgende

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

In jouw geval xs = xen y = 40.
Als len(x) groot is, wordt dit inefficiënt en moet u echt axhlinegebruiken.


Antwoord 7, autoriteit 33%

Je kunt plt.gridgebruiken om een horizontale lijn te tekenen.

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

Other episodes