matplotlib中的figsize不会更改图形大小吗

matplotlib中的figsize不会更改图形大小吗

本文介绍了matplotlib中的figsize不会更改图形大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,代码生成的条形图不太清晰,我想将数字放大,以便可以更好地看到这些值.这没有做.正确的方法是什么?x是数据框,x['user']是图中的x轴,x['number']是y.

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

带有plt.figure的行不会更改初始尺寸.

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

推荐答案

一个选项(如@tda所述),最好/最标准的方法是将plt.figure放在plt.bar之前:

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

如果要在创建图形后设置图形大小,另一种方法是使用 fig.set_size_inches (请注意,我使用了 plt.gcf 此处获取当前数字):

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)

尽管不是最干净的代码,也可以一行完成全部操作.首先,您需要创建图形,然后获取当前轴( fig.gca ),然后在其上绘制Barplot:

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

最后,我将指出,使用matplotlib面向对象方法通常会更好,在该方法中,您可以保存对当前图形和轴的引用,并直接在其上调用所有绘图功能.它可能会增加更多的代码行,但通常是更清晰的代码(并且您可以避免使用gcf()gca()之类的东西).例如:

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

这篇关于matplotlib中的figsize不会更改图形大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:12