Python matplotlib 中的 figsize 没有改变图形大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52274643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
figsize in matplotlib is not changing the figure size?
提问by user10341548
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.
正如您所看到的,代码生成了一个不太清晰的条形图,我想让图形更大,以便更好地看到值。这不行。什么是正确的方法?x 是一个数据框,x['user']
是图中的 x 轴,x['number']
是 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.
带有 plt.figure 的线不会改变初始尺寸。
回答by tmdavison
One option (as mentioned by @tda), and probably the best/most standard way, is to put the plt.figure
before the plt.bar
:
一种选择(如@tda 提到的),并且可能是最好/最标准的方法,是将 放在plt.figure
之前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):
另一种选择,如果你想在创建图形后设置图形大小,是使用fig.set_size_inches
(注意我plt.gcf
在这里使用的是获取当前图形):
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:
可以在一行中完成所有这些,尽管它不是最干净的代码。首先,您需要创建图形,然后获取当前轴 ( fig.gca
),并在其上绘制条形图:
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:
最后,我会注意到使用 matplotlib 面向对象的方法通常会更好,在这种方法中,您可以保存对当前 Figure 和 Axes 的引用,并直接调用它们上的所有绘图函数。它可能会添加更多的代码行,但它通常是更清晰的代码(并且您可以避免使用诸如gcf()
和 之类的东西gca()
)。例如:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
ax.bar(x['user'], x['number'], color="blue")
回答by tda
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")