# Plot Positioning

Last updated: July 2nd, 2019

# Plot positioningÂ¶

Although we have already seen an example of positioning in this case we will see what possibilities we have in the market for the management of sizes, multigraphic grids, etc.

## Hands on!Â¶

InÂ [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

InÂ [2]:
diamonds = pd.read_table('data/diamonds.txt', sep=',')


## Figures and subfiguresÂ¶

When we call the subplots() function we get a tuple containing a Figure and a axes element.

InÂ [3]:
plot_objects = plt.subplots()

fig, ax = plot_objects

ax.plot([1,2,3], [1,2,3])

plot_objects

Out[3]:
(<Figure size 432x288 with 1 Axes>,
<matplotlib.axes._subplots.AxesSubplot at 0x7f0dd6a287f0>)

We can also define how many elements we want inside our figure. To do that we can set the nrows and ncols params.

InÂ [4]:
plot_objects = plt.subplots(nrows=2, ncols=2, figsize=(14, 6))

fig, ((ax1, ax2), (ax3, ax4)) = plot_objects

plot_objects

Out[4]:
(<Figure size 1008x432 with 4 Axes>,
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f0dd696b198>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f0dd491ce80>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7f0dd48cd518>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f0dd4877ba8>]],
dtype=object))
InÂ [5]:
ax1.plot(np.random.randn(50), c='red', linestyle='--')
ax2.plot(np.random.randn(50), c='green', linestyle=':')
ax3.plot(np.random.randn(50), c='blue', marker='o', linewidth=3.0)
ax4.plot(np.random.randn(50), c='yellow')

fig

Out[5]:

## Â Size of plotsÂ¶

As it has been seen so far, the default size of the graphics rendering may not always be adequate (generally, excessively small if the number of elements in the graphic is high).

In order to modify the size of the resulting graph, as we have seen, matplotlib offers us the function figure and the attribute figsize. Keep in mind that the size of the graph must be set prior to calling any of the pyplot functions.

InÂ [6]:
cuts = list(diamonds['cut'].unique())

x_values = [cuts.index(element) + np.random.uniform(-0.3, 0.3) for element in diamonds['cut']]
y_values = diamonds['price']

plt.figure(figsize=(10, 7))

plt.scatter(x_values, y_values, color="black", alpha=0.1)

plt.ylim(-0.5, 20000)
plt.title("Price vs. Cut", weight="bold", size=15, color="0.3")
plt.xlabel("Cut", weight="bold", size=12)
plt.ylabel("Price", weight="bold", size=12)
plt.xticks(range(0, 5), cuts, rotation=45)

plt.show()


## Â Multiple plotsÂ¶

In matplotlib, to have multiple graphics within the same plot, we have to define the dimensions of the grid in which we will paint each graph and we have to manually place each figure in the place that corresponds to him.

To make use of this positioning, matplotlib offers us the subplot2grid.

InÂ [7]:
cuts = list(diamonds['cut'].unique())

plt.figure(figsize=(12, 3))

for i, element in enumerate(cuts):
plt.subplot2grid((1, len(cuts)), (0, i))
plt.hist(diamonds[diamonds['cut'] == element].loc[:, 'carat'].values)
plt.title(element)

InÂ [8]:
cuts = list(diamonds['cut'].unique())

plt.figure(figsize=(10, 10))

for i, element in enumerate(cuts):
plt.subplot2grid((len(cuts), 1), (i, 0))
plt.hist(diamonds[diamonds['cut'] == element].loc[:, 'carat'].values)
plt.title(element)

InÂ [9]:
cuts = list(diamonds['cut'].unique())

plt.figure(figsize=(10, 10))

for i, element in enumerate(cuts):
plt.subplot2grid((len(cuts), 1), (i, 0))
plt.hist(diamonds[diamonds['cut'] == element].loc[:, 'carat'].values)
plt.title(element)

plt.tight_layout()


## Â SubplotsÂ¶

In addition to enabling the positioning of graphics in the form of a grid, matplotlib allows us to include one graphic within another, so that we take advantage of the empty areas of a graphic to show additional information.

To do this, matplotlib allows us to define the position of a new coordinate axis (using the function axes) and the call to any function of pyplot on this new axis.

InÂ [10]:
plt.figure(figsize=(10, 10))

plt.scatter(diamonds.carat, diamonds.price, color="green", alpha=0.1)

plt.xlim(0, 6)

detail_axes = plt.axes([0.58, 0.18, 0.3, 0.3])
detail_axes.scatter(diamonds.carat[(diamonds.price >= 200) & (diamonds.price <= 1700)],
diamonds.price[(diamonds.price >= 200) & (diamonds.price <= 1700)],
color="red", alpha=0.1)

Out[10]:
<matplotlib.collections.PathCollection at 0x7f0dd35259e8>