figsize in matplotlib is not changing the figure size?

Question:

As you can see the code produces a barplot that is not as clear and I want to make the figure larger so the values can be seen better. This doesn’t do it. What is the correct way?
x is a dataframe and x['user'] is the x axis in the plot and x['number'] is the y.

import matplotlib.pyplot as plt
%matplotlib inline  
plt.bar(x['user'], x['number'], color="blue")
plt.figure(figsize=(20,10)) 

The line with the plt.figure doesn’t change the initial dimensions.

Asked By: user10341548

||

Answers:

Try setting up the size of the figure before assigning what to plot, as below:

import matplotlib.pyplot as plt
%matplotlib inline  

plt.figure(figsize=(20,10)) 
plt.bar(x['user'], x['number'], color="blue")
Answered By: tda

One option (as mentioned by @tda), and probably the best/most standard way, is to put the plt.figure before the plt.bar:

import matplotlib.pyplot as plt

plt.figure(figsize=(20,10)) 
plt.bar(x['user'], x['number'], color="blue")

Another option, if you want to set the figure size after creating the figure, is to use fig.set_size_inches (note I used plt.gcf here to get the current figure):

import matplotlib.pyplot as plt

plt.bar(x['user'], x['number'], color="blue")
plt.gcf().set_size_inches(20, 10)

It is possible to do this all in one line, although its not the cleanest code. First you need to create the figure, then get the current axis (fig.gca), and plot the barplot on there:

import matplotlib.pyplot as plt

plt.figure(figsize=(20, 10)).gca().bar(x['user'], x['number'], color="blue")

Finally, I will note that it is often better to use the matplotlib object-oriented approach, where you save a reference to the current Figure and Axes and call all plotting functions on them directly. It may add more lines of code, but it is usually clearer code (and you can avoid using things like gcf() and gca()). For example:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
ax.bar(x['user'], x['number'], color="blue")
Answered By: tmdavison
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.