What is the necessity of plt.figure() in matplotlib?
Question:
plt.figure(figsize=(10,8))
plt.scatter(df['attacker_size'][df['year'] == 298],
# attacker size in year 298 as the y axis
df['defender_size'][df['year'] == 298],
# the marker as
marker='x',
# the color
color='b',
# the alpha
alpha=0.7,
# with size
s = 124,
# labelled this
label='Year 298')
In the above snippet of code collected from Scatterplot in Matplotlib, what is the necessity of plt.figure()
?
Answers:
It is not always necessary because a figure
is implicitly created when you create a scatter
plot; however, in the case you have shown, the figure is being created explicitly using plt.figure
so that the figure will be a specific size rather than the default size.
The other option would be to use gcf
to get the current figure after creating the scatter
plot and set the figure size retrospectively:
# Create scatter plot here
plt.gcf().set_size_inches(10, 8)
The purpose of using plt.figure()
is to create a figure object.
The whole figure is regarded as the figure object. It is necessary to explicitly use plt.figure()
when we want to tweak the size of the figure and when we want to add multiple Axes objects in a single figure.
# in order to modify the size
fig = plt.figure(figsize=(12,8))
# adding multiple Axes objects
fig, ax_lst = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
plt.figure(figsize=(10,8))
plt.scatter(df['attacker_size'][df['year'] == 298],
# attacker size in year 298 as the y axis
df['defender_size'][df['year'] == 298],
# the marker as
marker='x',
# the color
color='b',
# the alpha
alpha=0.7,
# with size
s = 124,
# labelled this
label='Year 298')
In the above snippet of code collected from Scatterplot in Matplotlib, what is the necessity of plt.figure()
?
It is not always necessary because a figure
is implicitly created when you create a scatter
plot; however, in the case you have shown, the figure is being created explicitly using plt.figure
so that the figure will be a specific size rather than the default size.
The other option would be to use gcf
to get the current figure after creating the scatter
plot and set the figure size retrospectively:
# Create scatter plot here
plt.gcf().set_size_inches(10, 8)
The purpose of using plt.figure()
is to create a figure object.
The whole figure is regarded as the figure object. It is necessary to explicitly use plt.figure()
when we want to tweak the size of the figure and when we want to add multiple Axes objects in a single figure.
# in order to modify the size
fig = plt.figure(figsize=(12,8))
# adding multiple Axes objects
fig, ax_lst = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes