我正在尝试使用matplotlib绘制右延伸的水平线,但我找不到我需要您帮助的方法。
1-我有一个带有日期,价格和指标值的熊猫df
2-我想在一张图表中绘制价格,将其绘制为一条线,并且在价格之上,我还要绘制一条扩展线,其中指标值高于阈值,预期结果类似于此图。
在第二张屏幕截图中,您可以看到价格线上的那些彩色圆圈,我想将其替换为水平的右延长线。
数据.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()
答案 0 :(得分:1)
要在matplotlib
中绘制水平线,可以使用plt.axhline
:
plt.scatter(BW50['Close'], color="blue", label='BW50')
axhline
具有xmin
和xmax
参数,如果您希望线条不要水平填充图的话。
根据您的特定结果,可以尝试:
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()