Location of the legend in PyPlot

Hello, I am currently using PyPlot package for visualization. I tried to pull my legend outside the box like in the Legend guide:

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

However, the result cuts my legend. Here is the part of my figure which contains a legend:

What should I do in order to have a legend, say, like this

(this is the example from the same topic on stackoverflow, but I cannot repeat the result from there, too)

Thank you in advance!

It doesn’t automatically adjust the axis dimensions unfortunately.

x = 0:0.1:3*pi
y = sin(x)
z = cos(x)
ax = axes()
plot(x,y,label="sin(x)")
plot(x,z,label="cos(x)")
grid("on")
legend(bbox_to_anchor=[1.05,1],loc=2,borderaxespad=0)
ax[:set_position]([0.06,0.06,0.71,0.91])

2 Likes

Thank you! Also, I have additional question if you don’t mind. Is there any convenient way to control the font size in PyPlot? The problems is that if you insert your image in .pdf, the letters are usually too small. Right now I adjust the font size manually every time, i.e. use

xlabel("t",fontsize = 20)
ylabel("x",fontsize = 20)
title("Something", fontsize = 20)

etc.
The problem is that this is very inconvenient. Also, I cannot change the yticks size for some reason:

yticks(fontsize = 20)

returns

ERROR: function Int64 does not accept keyword arguments in kwfunc(::Any) at .\boot.jl:236

for some reason.

It works with xticks, though.

I have seen in this post that in Python there is the way to do this simpler with

params = {'legend.fontsize': 'x-large',
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}

Is it possible to do something like this with Julia language?

Thank you in advance!

What’s your goal exactly? Are you trying to change the axis number font size or the label font size?

x = 0:0.1:3*pi
y = sin(x)
z = cos(x)
ax = axes()
plot(x,y,label="sin(x)")
plot(x,z,label="cos(x)")
grid("on")
myfont = Dict("fontname"=>"Sans","weight"=>"semibold","fontsize"=>22)
xlabel("x",fontdict=myfont)
ylabel("y",fontdict=myfont)
title("Test",fontdict=myfont)

Take a look at this PyPlot Cookbook for more reference. Search for font to see other usages.

I would like to change both. Tried to find this in PyPlot Cookbook, but it seems it is not mentioned there.

Add labelsize=16 to line 49 of the majorminor example.

ax[:xaxis][:set_tick_params](which="major",length=10,width=2,labelsize=16)

For more tick properties see this matplotlib documentation.

It is rather irritating that it is so inconsistent.

2 Likes

You should be able to use one of the matplotlibrc global settings.