When I try and change the legend fontsize using PyPlot from julia, I get an error message saying "Pyerror..got an unexpected key word "'fontsize'". This happens when I try both of the standard formulations shown below:
ax[:legend]( ("Data", "Model Predictions"),fontsize=4,loc=4 )
ax[:legend]( ("Data", "Model Predictions"),prop={fontsize: "small"},loc=4 )
Note that changing fontsize works fine with other objects e.g. xlabel
Any ideas?
Does this work for you?
using PyPlot
fig, ax = PyPlot.subplots()
ax[:plot](rand(10), rand(10), label = "Data")
ax[:legend](loc="best", fontsize=4)
If not, what versions of Julia, PyPlot, PyCall, and Python are you on?
The help for legend states that:
prop : None or :class:matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current
:data:matplotlib.rcParams will be used.
So the prob keyword argument expects a dict with font properties. Dicts is constructed in julia as [key => val]. This dict can then contain the properties. The property you would like to set is size and not fontsize because the prob keyword argument only contains font properties.
ax[:legend](("Data", "Model Predictions"), prop=["size" => "small"], loc=4)
In the end the above two suggestions didn't work (I think it's a version issue). But this did:
using PyPlot
#pyimport matplotlib.pyplot as plt
#pyimport matplotlib.font_manager as fm
prop = fm.FontProperties(size=9)
fig, ax = PyPlot.subplots()
ax[:plot](rand(10), rand(10), label = "Data")
ax[:legend](loc="best", prop=prop)
Related
I am creating a figure in Matplotlib like this:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')
I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?
Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')
For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):
axes.titlesize : large # fontsize of the axes title
axes.labelsize : medium # fontsize of the x any y labels
(As far as I can see, there is no way to set x and y label sizes separately.)
And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.
You can also do this globally via a rcParams dictionary:
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
If you're more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:
import matplotlib.pyplot as plt
# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)
# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium') # relative to plt.rcParams['font.size']
# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()
I don't know of a similar way to set the suptitle size after it's created.
To only modify the title's font (and not the font of the axis) I used this:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
The fontdict accepts all kwargs from matplotlib.text.Text.
Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.
Globally setting font sizes via rcParams should be done with
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16
# or
params = {'axes.labelsize': 16,
'axes.titlesize': 16}
plt.rcParams.update(params)
# or
import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)
# or
axes = {'labelsize': 16,
'titlesize': 16}
mpl.rc('axes', **axes)
The defaults can be restored using
plt.rcParams.update(plt.rcParamsDefault)
You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is
axes.labelsize: 16
axes.titlesize: 16
If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via
plt.style.use('mystyle')
# or, for a single section
with plt.style.context('mystyle'):
# ...
You can also create (or modify) a matplotlibrc file which shares the format
axes.labelsize = 16
axes.titlesize = 16
Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.
A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)
axes.labelsize - Fontsize of the x and y labels
axes.titlesize - Fontsize of the axes title
figure.titlesize - Size of the figure title (Figure.suptitle())
xtick.labelsize - Fontsize of the tick labels
ytick.labelsize - Fontsize of the tick labels
legend.fontsize - Fontsize for legends (plt.legend(), fig.legend())
legend.title_fontsize - Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.
all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by
font.size - the default font size for text, given in pts. 10 pt is the standard value
Additionally, the weight can be specified (though only for the default it appears) by
font.weight - The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).
If you aren't explicitly creating figure and axis objects you can set the title fontsize when you create the title with the fontdict argument.
You can set and the x and y label fontsizes separately when you create the x and y labels with the fontsize argument.
For example:
plt.title('Car Prices are Increasing', fontdict={'fontsize':20})
plt.xlabel('Year', fontsize=18)
plt.ylabel('Price', fontsize=16)
Works with seaborn and pandas plotting (when Matplotlib is the backend), too!
Others have provided answers for how to change the title size, but as for the axes tick label size, you can also use the set_tick_params method.
E.g., to make the x-axis tick label size small:
ax.xaxis.set_tick_params(labelsize='small')
or, to make the y-axis tick label large:
ax.yaxis.set_tick_params(labelsize='large')
You can also enter the labelsize as a float, or any of the following string options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', or 'xx-large'.
An alternative solution to changing the font size is to change the padding. When Python saves your PNG, you can change the layout using the dialogue box that opens. The spacing between the axes, padding if you like can be altered at this stage.
Place right_ax before set_ylabel()
ax.right_ax.set_ylabel('AB scale')
libraries
import numpy as np
import matplotlib.pyplot as plt
create dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))
Create bars and choose color
plt.bar(x_pos, height, color = (0.5,0.1,0.5,0.6))
Add title and axis names
plt.title('My title')
plt.xlabel('categories')
plt.ylabel('values')
Create names on the x axis
plt.xticks(x_pos, bars)
Show plot
plt.show()
7 (best solution)
from numpy import*
import matplotlib.pyplot as plt
X = linspace(-pi, pi, 1000)
class Crtaj:
def nacrtaj(self,x,y):
self.x=x
self.y=y
return plt.plot (x,y,"om")
def oznaci(self):
return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)
6 (slightly worse solution)
from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
def __init__(self,m):
self.m=m
def srednja(self):
redovi = len(M)
stupci = len (M[0])
lista=[]
a=0
suma=0
while a<stupci:
for i in range (0,redovi):
suma=suma+ M[i,a]
lista.append(suma)
a=a+1
suma=0
b=array(lista)
b=b/redovi
return b
OBJ = AriSred(M)
sr = OBJ.srednja()
I am a bit lost on the best approach to add labels to my markers with a seaborn relplot. I see in the matplotlib documentation that there is a axes.text() method that looks to be the right approach, but it doesn't appear that this method exists. Does seaborn behave differently than matplotlib in this sense? What would the right approach be?
Error:
AttributeError: 'numpy.ndarray' object has no attribute 'text'
Code:
line_minutes_asleep = sns.relplot(
x = "sleep_date",
y = "minutes_asleep",
kind = "line",
data = df,
height=10, # make the plot 5 units high
aspect=3
)
x = df.sleep_date
y = df.minutes_asleep
names = df.minutes_asleep
print(line_minutes_asleep.axes.text())
relplot returns a FacetGrid, which is a figure containing several subplots. The property .axes of a FacetGrid is a 2D ndarray of Axes objects. Therefore, you need to use FacetGrid.axes[i,j] to get a reference to the subplot.
If you want to write something in the first subplot (axes[0,0]), at the position x,y=(20,5), you would need to do:
import seaborn as sns
sns.set(style="ticks")
tips = sns.load_dataset("tips")
g = sns.relplot(x="total_bill", y="tip", hue="day", data=tips)
g.axes[0,0].text(20,5,"this is a text")
I am trying to generate a plot with matplotlib and I use the 'stix' font (rcParams['mathtext.fontset'] = 'stix') in order to have smooth font size transitions from text to math text. However, some of my math symbols I want to be Italic (scalar values) and some to be Italic AND Bold (tensors). I do not want to go through the solution of using Latex rendering cause then other things are messed up.
I will give you a small example that depicts the problem:
from numpy import *
from matplotlib.pyplot import *
# Chaning font to stix
rcParams['mathtext.fontset'] = 'stix'
# Some data to constract this plotting example
datax=[0,1,2]
datay=[8,9,10]
datay2=[8,15,10]
fig, ay = subplots()
ay.plot(datax, datay, color="0.", ls='-', label= r"$F_{\alpha}$")
ay.plot(datax, datay2, color="0.", ls='-', label=r"$\mathbf{F_{\alpha}}$")
# Now add the legend with some customizations.
legend = ay.legend(loc='left', shadow=True)
#frame = legend.get_frame()
#frame.set_facecolor('0.90')
xlabel(r"x label",fontsize=18)
ylabel(r'y label', fontsize=18)
grid()
show()
If you run the code the first label is Italic and the second label is Bold. How could I achieve the second label to be Bold AND Italic?
Problem with math text to be Italic and bold
A few more specific mathtext params are needed:
from numpy import *
from matplotlib.pyplot import *
# Changing font to stix; setting specialized math font properties as directly as possible
rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.it'] = 'STIXGeneral:italic'
rcParams['mathtext.bf'] = 'STIXGeneral:italic:bold'
# Some data to construct this plotting example
datax=[0,1,2]
datay=[8,9,10]
datay2=[8,15,10]
fig, ay = subplots()
ay.plot(datax, datay, color="0.", ls='-', label= r"$\mathit{F_{\alpha}}$")
ay.plot(datax, datay2, color="0.", ls='-', label=r"$\mathbf{F_{\alpha}}$")
# Now add the legend with some customizations.
legend = ay.legend(loc='left', shadow=True)
# Using the specialized math font again
xlabel(r"$\mathbf{x}$ label",fontsize=18)
ylabel(r'y label', fontsize=18)
grid()
show()
Note that I used the mathbf in an axis label, too. Would probably change the rest of the label to a STIX font, which you can define a non-italic-non-bold case of: see the docs under 'Custom fonts'.
There are also at least two examples in the matplotlib Gallery that might help: one looking at font families and another reminding us which STIX fonts are which.
So MatplotLib is using LaTeX syntax, so my best guess is that you can use LaTeX syntax for how to get italicized and bold, which is
\textbf{\textit{text}}
So in your case it would be
ay.plot(datax, datay2, color="0.", ls='-', label= r"$\mathbf{ \textit{F_{\alpha}} }$")
When trying to add a rectangle patch with a hatch pattern to a plot it seems that it is impossible to set the keyword argument edgecolor to 'none' when also specifying a hatch value.
In other words I am trying to add a hatched rectangle WITHOUT an edge but WITH a pattern filling. This doesnt seem to work. The pattern only shows up if I also allow an edge to be drawn around the rectangle patch.
Any help on how to achieve the desired behaviour?
You should use the linewidth argument, which has to be set to zero.
Example (based on your other question's answer):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
# generate some data:
x,y = np.meshgrid(np.linspace(0,1),np.linspace(0,1))
z = np.ma.masked_array(x**2-y**2,mask=y>-x+1)
# plot your masked array
ax.contourf(z)
# plot a patch
p = patches.Rectangle((20,20), 20, 20, linewidth=0, fill=None, hatch='///')
ax.add_patch(p)
plt.show()
You'll get this image:
I'm using some simple matplotlib functions to draw a pie chart:
f = figure(...)
pie(fracs, explode=explode, ...)
However, I couldn't find out how to set a default font color, line color, font size – or pass them to pie(). How is it done?
Showing up a bit late for the party but I encountered this problem and didn't want to alter my rcParams.
You can resize the text for labels or auto-percents by keeping the text returned from creating your pie chart and modifying them appropriately using matplotlib.font_manager.
You can read more about using the matplotlib.font_manager here:
http://matplotlib.sourceforge.net/api/font_manager_api.html
Built in font sizes are listed in the api;
"size: Either an relative value of ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ or an absolute font size, e.g. 12"
from matplotlib import pyplot as plt
from matplotlib import font_manager as fm
fig = plt.figure(1, figsize=(6,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
plt.title('Raining Hogs and Dogs')
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
patches, texts, autotexts = ax.pie(fracs, labels=labels, autopct='%1.1f%%')
proptease = fm.FontProperties()
proptease.set_size('xx-small')
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)
plt.show()
Global default colors, line widths, sizes etc, can be adjusted with the rcParams dictionary:
import matplotlib
matplotlib.rcParams['text.color'] = 'r'
matplotlib.rcParams['lines.linewidth'] = 2
A complete list of params can be found here.
You could also adjust the line width after you draw your pie chart:
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8,8))
pieWedgesCollection = plt.pie([10,20,50,20],labels=("one","two","three","four"),colors=("b","g","r","y"))[0] #returns a list of matplotlib.patches.Wedge objects
pieWedgesCollection[0].set_lw(4) #adjust the line width of the first one.
Unfortunately, I can not figure out a way to adjust the font color or size of the pie chart labels from the pie method or the Wedge object. Looking in the source of axes.py (lines 4606 on matplotlib 99.1) they are created using the Axes.text method. This method can take a color and size argument but this is not currently used. Without editing the source, your only option may be to do it globally as described above.
matplotlib.rcParams['font.size'] = 24
does change the pie chart labels font size