Profile picture

2.6 - Plot Positioning

Last updated: February 16th, 20192019-02-16Project preview

rmotr


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.

purple-divider

Hands on!

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

%matplotlib inline
In [ ]:
diamonds = pd.read_table('data/diamonds.txt', sep=',')

green-divider

Figures and subfigures

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

In [ ]:
plot_objects = plt.subplots()

fig, ax = plot_objects

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

plot_objects

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

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

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

plot_objects
In [ ]:
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

green-divider

 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 [ ]:
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()

green-divider

 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 [ ]:
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 [ ]:
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 [ ]:
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()

green-divider

 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 [ ]:
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)

purple-divider

Notebooks AI
Notebooks AI Profile20060