python22.sci2u.dk Active sci2u
Loading...
Login
Prefer latest booklet Prefer latest booklet Login
Link to booklet is copied to clipboard!
Saved to booklet!
Removed from booklet!
Started capturing to booklet.
Stopped capturing to booklet.
Preferring latest booklet.
No longer prefers latest booklet.
Entered edit mode.
Exited edit mode.
Edit mode

Click on the booklet title or a chapter title to edit (max. 30 characters)


Python book

Basic Python Numerical Python Plotting with Matplotlib
3.1 Text in plots
3.2 Two plots
3.3 Bar and scatter plots
3.4 Fontsizes
3.5 Cool colors
3.6 General help pages
Advanced Python Add Chapter..

Plotting with Matplotlib

3.1 Text in plots

Default choices in Matplotlib are changed via the method pyplot.rc(). Here is an example, where the default font size is increased with the plt.rc('font', size=16) statement:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

plt.rc('font', size=16)
fig, ax = plt.subplots()


theta = np.linspace(0,3*np.pi,200)
t = 0.1
p = 10
x = theta * (np.cos(theta) - t * np.sin(p*theta))
y = theta * (np.sin(theta) + t * np.cos(p*theta))

ax.plot(x,y)

Figure 1

A title, axis labels, and some text is added with these commands:
ax.plot(x,y)
ax.set_title('Clouds')
ax.set_xlabel('horizontal')
ax.set_ylabel('vertical')
ax.text(-8,-4,'Sky')
fig.tight_layout()
where the final fig.tight_layout() call assures that the labels are not clipped when the figure is stored in a file with the fig.savefig() method call:
fig.savefile('myfilename.png')

Figure 2



3.2 Two plots

Several plots can be managed with the plt.subplots() method:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
theta = np.linspace(0,2*np.pi,100)
x = np.cos(theta)
y = np.sin(theta)

plt.rc('font', size=16)
fig, axs = plt.subplots(1, 2, figsize=(10,2))
ax = axs[0]
ax.set_aspect('equal')
ax.grid()
ax.plot(x,y)

ax = axs[1]
ax.grid()
ax.plot(2*x,2*y)
The 1, 2 arguments to subplots() declare one row and two columns of subfigures, and the figsize=(10,2) declares the size of the drawing area in inches. Text with some font size will appear differently sized on figures with different figsize settings. The resulting figure looks like this:

Figure 3

The two variables in the tuple, fig, axs, being assigned the output of the plt.subplots() call can be used to access the drawing objects. The first variable, fig, is the entire drawing to be used if the drawing is to have a headline if it is to be saved to a file as done with these commands:
fig.suptitle('Headline')
fig.savefig('myfilename.png')

Figure 4

The second variable, axs, becomes a list of so-called axes (i.e. matplotlib.Axes-objects). They are accessed as axs[0], axs[1], etc. as done above. Whenever a method is accessed on one axis, e.g. axs[0].grid(), only the subfigure described by this axis is affected. In the example, there is a axs[0].set_aspect('equal') statement but no axs[1].set_aspect('equal') and hence only the first subfigure is affected. The consequence of the .set_aspect('equal') method call is, as can be seen, that a unit length appears to have the same length, whether plotted on the - or on -axis. Hence the curve being plotted looks like a circle in the left-hand subplot controlled by axs[0] while it does not in the right-hand subplot controlled by axs[1]
By looping over both axes when calling the .set_aspect('equal') method:
fig, axs = plt.subplots(1, 2, figsize=(10,2), sharey=True)
for a in axs:
    a.set_aspect('equal')
    a.grid()
axs[0].plot(x,y)
axs[1].plot(2*x,2*y)
we can have the circle appear correctly in both subplots:

Figure 5

where further the sharey=True argument assures that the two subplots have the same tick settings on the -axis and that the values are only printed on the left-most subplot.


3.3 Bar and scatter plots

N = 5
x = np.arange(N)
y = np.random.rand(N)

fig, axs = plt.subplots(1, 2, figsize=(10,2))
for a in axs:
    a.grid()
axs[0].bar(x,y)
axs[1].scatter(x,y)

Figure 6

for a in axs:
    a.set_xticks(range(5))
    a.set_yticks([0,0.5,1])

Figure 7

axs[0].bar(x,y,color=('b','b','b','r','b'),edgecolor='black')
axs[1].scatter(x,y,100,marker='P',color=('b','b','b','r','b'))

Figure 8



3.4 Fontsizes

To change the fontsize in a plot you may write some of these commands:
import matplotlib.pyplot as plt

SMALL_SIZE = 16
MEDIUM_SIZE = 20
BIGGER_SIZE = 24
plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title


3.5 Cool colors

The colors define by the short names, 'b', 'r', etc. can be changed with these settings:
import matplotlib.colors as colors
colors.colorConverter.colors['b'] = [0, 0.4470, 0.7410]
colors.colorConverter.colors['r'] = [0.6350, 0.0780, 0.1840]
colors.colorConverter.colors['g'] = [0.4660, 0.6740, 0.1880]
colors.colorConverter.colors['c'] = [0.3010, 0.7450, 0.9330]
colors.colorConverter.colors['m'] = [0.4940, 0.1840, 0.5560]
colors.colorConverter.colors['y'] = [0.9290, 0.6940, 0.1250]
colors.colorConverter.colors['o'] = [0.8500, 0.3250, 0.0980]


3.6 General help pages

In general, it can be recommended that you visit the Matplotlib help pages to more about how to plot nicely with matplotlib. However, if you are new to Python and Matplotlib it might be difficult to read the official Matplotlib help pages.


Sci2u Assignment: 820
Delete "Python book"?
Once deleted this booklet is gone forever!
Block is found in multiple booklets!

Choose which booklet to go to:

© 2019-2022 Uniblender ApS