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.
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,...)
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With