关于python:matplotlib中的figsize是不是在改变数字大小?

figsize in matplotlib is not changing the figure size?

本问题已经有最佳答案,请猛点这里访问。

如您所见,代码生成的条形图不够清晰,我希望使数字更大,以便更好地看到值。这不行。正确的方法是什么?x是一个数据帧,x['user']是图中的x轴,x['number']是y轴。

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

带plt.figure的线条不会改变初始尺寸。


一种选择(如@tda所提到的)可能是最好/最标准的方法,将plt.figure置于plt.bar之前:

1
2
3
4
5
import matplotlib.pyplot as plt
%matplotlib inline  

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

如果要在创建图形后设置图形大小,另一个选项是使用fig.set_size_inches(注意,我在这里使用plt.gcf获取当前图形):

1
2
3
4
5
import matplotlib.pyplot as plt
%matplotlib inline  

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

虽然这不是最干净的代码,但可以在一行中完成这一切。首先您需要创建图形,然后获取当前轴(fig.gca),并在此绘制条形图:

1
2
3
4
import matplotlib.pyplot as plt
%matplotlib inline  

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

最后,我将注意到,使用Matplotlib面向对象的方法通常更好,在这种方法中,您可以保存对当前图形和轴的引用,并直接调用它们上的所有绘图函数。它可能会添加更多的代码行,但通常代码更清晰(并且可以避免使用诸如gcf()gca())。例如:

1
2
3
4
5
6
import matplotlib.pyplot as plt
%matplotlib inline

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


在分配要绘制的内容之前,请尝试设置图形的大小,如下所示:

1
2
3
4
5
import matplotlib.pyplot as plt
%matplotlib inline  

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