1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I don't know how I forgot about this property!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.