-
Notifications
You must be signed in to change notification settings - Fork 653
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to add legend to the plot? #181
Comments
Rajeev, In the meantime, if you want to play with matplotlib, you can try using the Alternatively if you would like to contribute code to mplfinance to make it easy for users to include legends, I would be happy to work together with you on getting that code correctly merged into mplfinance. All the best. Thanks for you interest in mplfinance. --Daniel |
Hi Daniel, All the best |
Plot chart to figure and axis object
This does the trick thanks to the help of mr. Daniel Goldfarb. |
@arthurpdesimone |
Hi, I'm Youngil Koh I think the sample code below would be helpful.
|
@YoungilKoh |
Thank you for your help. You're amazing |
I found an issue while following @YoungilKoh 's answer (#181 (comment)) It worked, but only one of the plots can display (see attachment). I'll need help on why only one of them is showing in the legends. I debugged it, and i think i know the issue, the legendHandles only gives one Line2D object when printed, this might be a hint that can help us find the problem |
Thanks for your comments! |
Here's my code: ap = [
make_addplot(pd.DataFrame(MACD), color='r', panel=1),
make_addplot(pd.DataFrame(Signal), color='b', panel=1)
]
axes: List[Axes]
fig, axes = plot(
df, title='Graph',
type='candlestick',
style='yahoo', addplot=ap,
returnfig=True
)
axes[2].legend([None]*(len(ap)+2))
handles = axes[2].get_legend().legendHandles
axes[2].legend(handles=handles, labels=['MACD', 'Signal']) Did some edits in the second call of Thank you for helping. |
Well out of nowhere, it just got fixed, i think its a new update, i used the same method. Thanks! |
hi, also need labels help w mplfinance. but you guys lost me per how i could adapt my code to do labels , in a script run in powershell, and save to a file.
i changed it to this, but get i dont understand how you could do the fig,axes part AFTER you call mpf.plot. like that would have to be before .plot() call which has the savefig= param. i do have 3 panels. candles, stock and macd. but im lost per how to get labels on the plot and save it to a file from a script.
|
The problem, I think, is in this line of code: fig, axes = mpf.plot(df.tail(200), type='candle', volume=True, mav=(26, 50, 75, 100, 150),
addplot=list(ap2.values()), style='charles', savefig=save) change fig, axes = mpf.plot(df.tail(200), type='candle', volume=True, mav=(26, 50, 75, 100, 150),
addplot=list(ap2.values()), style='charles', returnfig=True) |
this helped BUT how do i get proper colors on other panels ....lost a whole day experimenting , no luck. thanks in advance
ap3 = {
you see ax6 , the stochrsi subplot on the bottom....i dont understand how to reference that handles of legend should be the correct colors. its obviuosly giving the colors of the top panels first 2...but no matter what i tried n read in the docs, i couldnt find examples both ref'd panels legend and from a addplot list. |
Have you tried using Also, I'm confused by something in your code: The code appears to be putting StochRSI on panel 2, and macd on panel 3. But in the plot image StochRSI is on the bottom panel (panel 3) and MACD is just above that (panel 2). I would also point out that the StochRSI panel has y-ticks on both the left and right, which suggests that between 'stochrsi_K' and 'stochrsi_D', one of them may be using axes[7] and the other axes[6]. If this is what you want, fine. If not, then you can code specifically |
Also, one other point to keep in mind, that may have an effect: Keep in mind that if you don't specify |
YES , thanks, my mistake flipping the labels and secondary_y all being true. fixed that!
THANKS and hope the mulitpanel legend struggle of mine helps people |
There is no question. Posting your struggles here definitely helps other mplfinance users. Not only does it help them directly, but it will help them indirectly in the future, as it is my intention to implement a Two addition things:
Finally, let me just say that your plot is one of the best mplfinance plots I have ever seen! Really, excellent job! Thank you for sharing! All the best. --Daniel |
This gives error:
Couldn't find what is the cause of error. Can anybody help? |
with subplots it's easy👍👍 fig , ax =plt.subplots(3,1,sharex=True,figsize=(10,10),gridspec_kw= {'height_ratios':[3,2,2]}) fig.set_edgecolor('k') p2 = [ mpf.make_addplot(data['High'],color='g',ax=ax[2]), mpf.plot(data,type='candle',ax=ax[0], addplot=p2 ,style='blueskies',volume=ax[1],mav=(6,9)) ax[0].legend(labels=['nolegend','nolegend','mav6','mav9']) plt.tight_layout() |
Support for legends is a very important capability for mplfinance to directly support. In the meantime, I really liked the sample code from Youngil Koh and it allowed me to succeed in my efforts to get proper legend display. My application is a bit complex and the addplots are conditionally created. To avoid rewriting it to conform to the example code, I decided to get the labels out of the addplot data structures. Here is the resulting code snippet and function which I created for my application. It creates the legend for the main panel (panel 0) or any of the sub panels.
|
wow! How do you get the candles etc so crips in your image from the mplfinance save file? would love mine to look like this. As an example, here's what my candles look like. not bad but it's not the view that i want and struggling to make it look crisper and larger in context of the overall saved image. also want to add the legend. Heres the code im using to save the file but it's still not quite right: Is there any updates on the LEGENDS capability within the package yet? |
You need to get the handles from the same subplot where you are intending to define the legend. In your code you have:
handles = axes[0].get_legend().legendHandles
which you use for the main plot, but when moving on to the subplots, you did not grab the handles again from those axes...
… On Jun 25, 2023, at 5:32 PM, TraderMan999 ***@***.***> wrote:
this helped BUT how do i get proper colors on other panels ....lost a whole day experimenting , no luck. thanks in advance
The problem, I think, is in this line of code:
fig, axes = mpf.plot(df.tail(200), type='candle', volume=True, mav=(26, 50, 75, 100, 150),
addplot=list(ap2.values()), style='charles', savefig=save)
change savefig to returnfig=True :
fig, axes = mpf.plot(df.tail(200), type='candle', volume=True, mav=(26, 50, 75, 100, 150),
addplot=list(ap2.values()), style='charles', returnfig=True)
ap3 = {
"SuperTrend_Long": mpf.make_addplot(df['SUPERTl'].tail(tail_num), color='g'),
"SuperTrend_Short": mpf.make_addplot(df['SUPERTs'].tail(tail_num), color='r'),
"PSAR_Long": mpf.make_addplot(df['PSARl'].tail(tail_num), color='y'),
"PSAR_Short": mpf.make_addplot(df['PSARs'].tail(tail_num), color='y'),
"EMA_15": mpf.make_addplot(df['EMA_15'].tail(tail_num), color='#55'),
"EMA_20": mpf.make_addplot(df['EMA_20'].tail(tail_num), color='#99'),
"EMA_30": mpf.make_addplot(df['EMA_30'].tail(tail_num), color='#0000CC'),
"EMA_50": mpf.make_addplot(df['EMA_50'].tail(tail_num), color='#005500'),
"EMA_75": mpf.make_addplot(df['EMA_75'].tail(tail_num), color='#00CC00'),
"EMA_100": mpf.make_addplot(df['EMA_100'].tail(tail_num), color='#990000'),
"EMA_200": mpf.make_addplot(df['EMA_200'].tail(tail_num), color='#CC0000'),
"stochrsi_K": mpf.make_addplot(df['stochrsi_K_ultragtx'].tail(tail_num), color='g', panel=2), # panel 2 specified
"stochrsi_D": mpf.make_addplot(df['stochrsi_D_ultragtx'].tail(tail_num), color='b', panel=2), # panel 2 specified
"MACDh": mpf.make_addplot(df['MACDh_6_12_9'].tail(tail_num), color='r', secondary_y=True, panel=3),
"MACDs": mpf.make_addplot(df['MACDs_6_12_9'].tail(tail_num), color='b', secondary_y=True, panel=3)
}
print('making axes0 legend')
fig, axes = mpf.plot(df.tail(tail_num), type='candle', volume=True, addplot=list(ap3.values()), style='charles',
returnfig=True, title=('Last '+str(tail_num)+' candles'+fname), scale_width_adjustment=dict(lines=0.25))
axes[0].legend([None]*(len(ap3)+2))
handles = axes[0].get_legend().legendHandles
axes[0].legend(handles=handles[2:], labels=list(ap3.keys()), loc='upper left', fontsize='x-small')
#axes[0].legend(loc='upper left', fontsize='x-small')
# IPydisplay.Image(ourpath)
print(axes)
axes[4].set_ylabel("MACD")
axes[6].set_ylabel("StochRSI")
print(axes)
print(len(ap3))
try:
axes[4].legend([None]*(len(ap3)+2))
axes[4].legend(handles=handles[2:], labels=['MACDh', 'MACDs'], loc='center left', fontsize='x-small')
except Exception as e:
print('error making legend axis4')
print(e)
print('making axes6 legend')
try:
# axes[6].legend([None]*(len(ap3)+2))
# axes[6].legend([None]*(2+2))
#handles6 = axes[6].get_legend().legendHandles
axes[6].legend(handles=handles[2:], labels=['stochrsi_K', 'stochrsi_D'], loc='center left', fontsize='x-small')
except Exception as e:
print('error making legend axis6')
print(e)
fig.savefig('plots/'+fname, dpi=300)
<https://user-images.githubusercontent.com/97939226/175432610-9a387d8d-42ea-465c-83b5-b688073dffa7.png>
you see ax6 , the stochrsi subplot on the bottom....i dont understand how to reference that handles of legend should be the correct colors. its obviuosly giving the colors of the top panels first 2...but no matter what i tried n read in the docs, i couldnt find examples both ref'd panels legend and from a addplot list. thanks
wow! How do you get the candles etc so crips in your image from the mplfinance save file? would love mine to look like this.
As an example, here's what my candles look like. not bad but it's not the view that i want and struggling to make it look crisper and larger in context of the overall saved image. also want to add the legend.
https://ibb.co/g6cVcy8 <https://ibb.co/g6cVcy8>
Is there any updates on the LEGENDS capability within the package yet?
—
Reply to this email directly, view it on GitHub <#181 (comment)>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AD4NKOSLOV2EY6YFEQRXGELXNC4AXANCNFSM4OCESKDQ>.
You are receiving this because you commented.
|
i think youre responding to the code i copied from someone else |
Can anyone suggest what i can do different to make these candles appear relatively bigger on this image? ive spent hours changing the various figsize parameters, dpi, figscale, etc to no avail. Here's some sample code. mpf.plot(data,figscale=1.25,style='yahoo',type='candle',
update_width_config=dict(candle_linewidth=0.4),
title=newtitle,savefig=dict(fname='./flashcards/' + savedPlotFileName,dpi=400,bbox_inches='tight'),
#hlines=dict(hlines=[midnightOpen,londonhigh,londonlow,
# fib_62, fib_705, fib_79,fib_21, fib_295, fib_38],
# colors=['b','g','r','r','g','k','r','g','k']),
hlines=dict(hlines=[midnightOpen, londonhigh, londonlow],
colors=['b', 'g', 'r', 'r', 'g', 'k'],
linewidths=(1, 1, 1, 1, 1, 1),
linestyle=['dotted', 'dotted', 'dotted']),
fill_between=dict(y1=minlow,y2=minhigh,where=where_values, alpha=0.5, color='g')) |
There are a few things you can try, lsited here in the order of what I suspect is most likely to help:
|
thanks let me give that a try. weird i think youre right. i must have made a copy / paste error. let me post below for clarification The lower hlines are fibs im tracking but ive pondered the value of having them there when the actual candles are so far from them so that could also be a compromise with a little if then else logic i can add AND AS ALWAYS THANK YOU FOR THE QUICK RESPONSE. I LOVE HOW ENGAGED YOU ARE IN YOUR PRODUCT FOR YOUR USER COMMUNITY. ONE OF THE BEST! |
The ylim definitely helped. i can probably live with that. thanks for that suggestion |
How to add a legend to the plots? For example, if using several moving averages it will be useful to show a legend to map moving averages to line plots.
Is clear how this is done using matplotlib but I did not see an example of how to do so using the mplfinance package.
TIA,
The text was updated successfully, but these errors were encountered: