Reputation: 326
I am pretty new to using Matplotlib
I couldn't figure out how to apply the things I found to my own graph, so I decided to make my own post
I use this code to generate my bar chart:
p = (len(dfrapport.index))
p1 = p * 2.5
p2 = p * 1.5
height = dfrapport['aantal']
bars = dfrapport['soort']
y_pos = np.arange(len(bars))
plt.bar(y_pos, height, color = ['black', 'red','orange', 'yellow', 'green', 'blue', 'cyan'])
plt.title('Aantal noodstoppen per categorie')
plt.xlabel('categorieën')
plt.ylabel('aantal')
plt.tick_params(axis='x', which='major', labelsize=p2)
plt.xticks(y_pos, bars)
plt.show()
But I don't understand how to change the size of the plot?
because when I use plt.figure(figsize=(p1,p2))
I get an empty plot with the correct labels ( But it does apply the size to the piechart i create later? ) And the barchart i originally wanted to create has basic 1-8 labels.
I want to change the size based on the amount of bars are created because sometimes the data I use doesn't contain one of the categories.
Upvotes: 0
Views: 450
Reputation: 339052
plt.figure(figsize=(p1,p2))
is the correct approach. The question is hence a bit unclear, because you just need to put it in your code, e.g.
p = (len(dfrapport.index))
p1 = p * 2.5
p2 = p * 1.5
plt.figure(figsize=(p1,p2))
# ...
plt.bar(...)
This is also shown in the question: How do you change the size of figures drawn with matplotlib?
Upvotes: 1
Reputation: 13999
With as few changes as humanly possible to your current code, the way to do this is to add the following line right after you define p1
and p2
:
plt.gcf().set_size_inches(p1,p2)
The above will set the size of the current Figure
object that pyplot
is using to make plots. In the future, you may way to switch over to using the Axes
-based interface to Matplotlib, as it's much more powerful and flexible in general:
p = (len(dfrapport.index))
p1 = p * 2.5
p2 = p * 1.5
height = dfrapport['aantal']
bars = dfrapport['soort']
y_pos = np.arange(len(bars))
fig = plt.figure(figsize=(p1,p2))
ax = fig.gca()
ax.bar(y_pos, height, color = ['black', 'red','orange', 'yellow', 'green', 'blue', 'cyan'])
ax.set_title('Aantal noodstoppen per categorie')
ax.set_xlabel('categorieën')
ax.set_ylabel('aantal')
ax.xaxis.set_tick_params(which='major', labelsize=p2)
ax.set_xticks(y_pos, bars)
fig.show()
Upvotes: 1