AttributeError when trying to change tittle and axis size matplotlib [duplicate] - matplotlib

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()

Related

Increasing Python table font in Jupyter

Upon trying to increase the size of a Matplotlib table generated from a csv file, the following code will not work to enlarge the font of the table's text:
plt.rcParams["figure.figsize"] = (8,5.5)
How can I increase the size of the font in Jupyter?
Perhaps something like this?
import matplotlib.pyplot as plt
header = ["header" for i in range(5)]
values = [["{}".format(c) for c in range(5)] for r in range(5)]
fig, ax = plt.subplots()
ax.set_axis_off()
table = ax.table(
cellText = values,
rowLabels = header,
colLabels = header,
cellLoc ='center',
loc ='upper left')
# this let you set the font
table.set_fontsize(15)
# the table doesn't scale with the font, you'll have to enlarge it manually
table.scale(1.5, 1.5)
ax.set_title('Example')
plt.show()

how to overlay a shapefile in matplotlib

In matplotlib how to overlay the shapefile (available in folder) as attached below at the top right position outside the plot.
The code referenced by banderkat:
import matplotlib.pyplot as plt
import Image
import numpy as np
im = Image.open('Jbc4j.jpg')
width = im.size[0]
height = im.size[1]
# We need a float array between 0-1, rather than
# a uint8 array between 0-255
im = np.array(im).astype(np.float) / 255
a = np.random.randint(0,100,100)
b = range(100)
fig = plt.figure(1,figsize=(5, 7), dpi=80, facecolor='w')
ax = fig.add_subplot(111)
ax.scatter(a,b)
fig.canvas.draw()
# With newer (1.0) versions of matplotlib, you can
# use the "zorder" kwarg to make the image overlay
# the plot, rather than hide behind it... (e.g. zorder=10)
fig.figimage(im, fig.bbox.xmax - width, fig.bbox.ymax - height, zorder=0)
# (Saving with the same dpi as the screen default to
# avoid displacing the logo image)
fig.savefig('temp.png', dpi=80)
plt.show()
Produces the following result (imaged cropped to save space).
Changing the zorder=1 will place the image on top.
Other helpful references:
How to change background color for scatter plot in matplotlib
How do you change the size of figures drawn with matplotlib?
Python/Matplotlib - Change the relative size of a subplot
In Matplotlib, what does the argument mean in fig.add_subplot(111)?
Customizing Location of Subplot Using GridSpec
You can use basemap toolkit to load and plot shapefile. Here I've plotted shapeFile in a separate axes and aligned it to top-right of other axes plot using 'subplot2grid'.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.gridspec as gridspec
def plotShapeFile():
# Lambert Conformal Conic map.
m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57.,
projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,
resolution ='l',area_thresh=1000.)
# read shapefile.
shp_info = m.readshapefile('C:/basemap-1.0.6/basemap-1.0.6/examples/huralll020','hurrtracks',drawbounds=False)
# find names of storms that reached Cat 4.
names = []
for shapedict in m.hurrtracks_info:
cat = shapedict['CATEGORY']
name = shapedict['NAME']
if cat in ['H4','H5'] and name not in names:
# only use named storms.
if name != 'NOT NAMED': names.append(name)
# plot tracks of those storms.
for shapedict,shape in zip(m.hurrtracks_info,m.hurrtracks):
name = shapedict['NAME']
cat = shapedict['CATEGORY']
if name in names:
xx,yy = zip(*shape)
# show part of track where storm > Cat 4 as thick red.
if cat in ['H4','H5']:
m.plot(xx,yy,linewidth=1.5,color='r')
elif cat in ['H1','H2','H3']:
m.plot(xx,yy,color='k')
# draw coastlines, meridians and parallels.
m.drawcoastlines()
m.drawcountries()
m.drawmapboundary(fill_color='#99ffff')
m.fillcontinents(color='#cc9966',lake_color='#99ffff')
m.drawparallels(np.arange(10,70,20),labels=[1,1,0,0])
m.drawmeridians(np.arange(-100,0,20),labels=[0,0,0,1])
if __name__ == '__main__':
fig=plt.figure()
plt.subplots_adjust(wspace=0.001, hspace=0.001)
ax1=plt.subplot2grid((5,5), (0,0), colspan=4, rowspan=4)
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
explode=(0, 0.05, 0, 0)
p1,t1,at1 = plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
plt.title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
ax2=plt.subplot2grid((5,5), (0,4), colspan=1, rowspan=1)
#draw shapeFile on the current active axes, i.e. ax2
plotShapeFile()
plt.tight_layout()
plt.show()
Below are links to references I've used:
http://sourceforge.net/projects/matplotlib/files/matplotlib-toolkits/basemap-1.0.6/
http://matplotlib.org/basemap/users/examples.html
Output:

hatched rectangle patches without edges in matplotlib

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:

Matplotlib: changing font size of exponent

I want to change the fontsize of the exponent as marked on the picture
I cannot use the matplotlib.rc('font', **font) method since I have different plots that need different font sizes so I change every element individually. I can however not find the font properties of the exponent.
If the exponent is an offset computed by matplotlib you can do the following to change the font size of the exponent to 30
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1,1.0001,100)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x)
t = ax.yaxis.get_offset_text()
t.set_size(30)
plt.show()

matplotlib: Controlling pie chart font color, line width

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