pceccon
pceccon

Reputation: 9844

Matplotlib using wide right margin - Python

I'm plotting a data with lots of information and I would like to use the whole area of the plot. However, even using tight_layout, I end up with a "wide" right margin. For example:

import matplotlib
import matplotlib.pyplot as plt

cmap = plt.get_cmap('Set3')
colors = [cmap(i) for i in numpy.linspace(0, 1, 18)]

data = numpy.random.rand(18, 365)

y = range(365)
plt.figure(figsize=(15,7))
for i in range(18):
    plt.plot(y, data[i, :], color=colors[i], linewidth=2)
plt.xticks(numpy.arange(0, 365, 10))
plt.tight_layout()

Produces something like:

enter image description here

I'd like to know how to get rid of this right margin, so the xtikcs used are could expand.

Upvotes: 1

Views: 197

Answers (2)

kikocorreoso
kikocorreoso

Reputation: 4219

You could do it in the following way:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

cmap = plt.get_cmap('Set3')
colors = [cmap(i) for i in np.linspace(0, 1, 18)]

data = np.random.rand(18, 365)

y = range(365)
fig, ax = plt.subplots(figsize=(15,7))
for i in range(18):
    ax.plot(y, data[i, :], color=colors[i], linewidth=2)
ax.set_xticks(np.arange(0, 365, 10))
ax.set_xlim(ax.xaxis.get_data_interval())
fig.tight_layout()

It is slightly more pythonic.

Upvotes: 0

The Dude
The Dude

Reputation: 4005

You can cut the right margin of by setting xlim. In your code add plt.xlim(0, 364) after you set the xticks. You can determine whatever section along the x-axis is plotted based on the two values you supply. When using actual data it is better to use the min and max values of your x array. In the example you supplied this means: plt.xlim(min(y), max(y)).

Upvotes: 2

Related Questions