I am trying to plot right extended horizontal lines using matplotlib and i have failed to find a way i need your help.
1- I have a pandas df with dates,prices and indicator values
2- i want to plot in one chart, the price as a line and also on top of the price i want to plot an extended line where my indicator values are above a threshold, the expected results is something like this picture.
The second screenshot you can see those colored circles on the price line I want to replace them with a horizontal right extended line. data.csv: https://drive.google.com/open?id=1ncTTvwJXVeh6dMHrIML7MpjlS-Yfox_o
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('plot_data.csv')
BW121 = df[['BW121','Close']]
BW121 = BW121.where(BW121.BW121>70).dropna()
BW50=df[['BW50','Close']]
BW50 = BW50.where(BW50.BW50>70).dropna()
LW121 =df[['LW121','Close']]
LW121 = LW121.where(LW121.LW121>70).dropna()
LW50 = df[['LW50','Close']]
LW50 = LW50.where(LW50.LW50>70).dropna()
plt.style.use('fivethirtyeight')
plt.scatter(BW121.index,BW121['Close'], color ="green",label='BW121')
plt.scatter(BW50.index , BW50['Close'], color ="blue", s=80,label='BW50')
plt.scatter(LW121.index , LW121['Close'], color ="red", s=80,label='LW121')
plt.scatter(LW50.index , LW50['Close'], color ="orange", s=80,label='LW50')
#Price Plot
plt.plot(df.index, df['Close'], marker='',alpha = 0.5,color='green')
plt.legend(loc='upper right')
plt.show()
To plot a horizontal line in matplotlib
you can use plt.axhline
:
plt.scatter(BW50['Close'], color="blue", label='BW50')
axhline
has xmin
and xmax
arguments if you'd rather the lines to not fill the plot horizontally.
Depending on what your specific outcome is, you could try:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('plot_data.csv')
BW121 = df[['BW121','Close']]
BW121 = BW121.where(BW121.BW121>70).dropna()
BW50=df[['BW50','Close']]
BW50 = BW50.where(BW50.BW50>70).dropna()
LW121 =df[['LW121','Close']]
LW121 = LW121.where(LW121.LW121>70).dropna()
LW50 = df[['LW50','Close']]
LW50 = LW50.where(LW50.LW50>70).dropna()
plt.style.use('fivethirtyeight')
plt.scatter(BW121.index,BW121['Close'], color ="green",label='BW121')
plt.scatter(BW50.index , BW50['Close'], color ="blue", s=80,label='BW50')
# axhline used here, one for each 'Close' value
for i in BW50['Close']:
plt.axhline(i, color ="blue", lw=0.5)
plt.scatter(LW121.index , LW121['Close'], color ="red", s=80,label='LW121')
plt.scatter(LW50.index , LW50['Close'], color ="orange", s=80,label='LW50')
# could repeat axhline here for other data etc.
#Price Plot
plt.plot(df.index, df['Close'], marker='',alpha = 0.5,color='green')
plt.legend(loc='upper right')
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.