Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

figsize in matplotlib is not changing the figure size? [duplicate]

Tags:

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.

like image 505
user10341548 Avatar asked Sep 11 '18 11:09

user10341548


People also ask

How do you change the size of figure drawn with matplotlib?

If you've already got the figure created, say it's 'figure 1' (that's the default one when you're using pyplot), you can use figure(num=1, figsize=(8, 6), ...) to change it's size etc. If you're using pyplot/pylab and show() to create a popup window, you need to call figure(num=1,...)

How does Figsize work in matplotlib?

figsize() takes two parameters- width and height (in inches). By default the values for width and height are 6.4 and 4.8 respectively. Where, x and y are width and height respectively in inches.

How do I change the height in matplotlib?

Set the Height and Width of a Figure in Matplotlib Instead of the figsize argument, we can also set the height and width of a figure. These can be done either via the set() function with the figheight and figwidth argument, or via the set_figheight() and set_figwidth() functions.


1 Answers

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") 
like image 185
tmdavison Avatar answered Sep 26 '22 13:09

tmdavison