0

So I am trying to plot a bar graph of this dataframe, Teams consists of strings, Mentions consists of ints. Trying to plot Teams on x-axis, and Mentions on y-axis. But I am getting problems with the y-axis labels where the increments and labels are in decimals and I want them in integers/whole numbers:

top_5_teams = ['England', 'France', 'Ireland', 'Italy', 'Wales']
top_5_team_mentions = [20, 11, 13, 6, 11]
df4 = pd.DataFrame({"Team":top_5_teams,
                      'Number of Times Mentioned':top_5_team_mentions})
df4 = df4.sort_values("Number of Times Mentioned", ascending=False)

df4_team = df4.iloc[:,0]
df4_mentions = df4.iloc[:,1]
plt.bar(arange(len(df4_team)),df4_mentions)
plt.xticks(arange(len(df4_team)),team,rotation=30)
plt.show()

This is my graph: enter image description here

I would like to do it based on a variable such as arange() rather than a single number like 20 or 25 so my code can be used with any dataframe. So how can I change it so the intervals on the y-axis are integers/whole numbers rather than decimals/floats?

parkjw96
  • 27
  • 3
  • can you please provide the minimal amount of data required for others to run your code. – baxx Sep 20 '20 at 01:05
  • Added the extra data – parkjw96 Sep 20 '20 at 05:36
  • `from matplotlib.ticker import MaxNLocator` and `plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))`. See [Matplotlib: How to force integer tick labels?](https://stackoverflow.com/questions/30914462/matplotlib-how-to-force-integer-tick-labels/34880501). – JohanC Sep 20 '20 at 12:00

1 Answers1

0

One of possible options is to use MultipleLocator, where you specify multiples of y value where ticks are to be printed (import matplotlib.ticker as tck required).

Another detail is that the drawing code can be more concise when you:

  • set the column to act as x axis as the index,
  • create the plot just from the DataFrame or from one of its columns.

So after you created your DataFrame, run just:

df4.set_index('Team').plot.bar(legend=None, rot=30)
plt.ylabel('Times mentioned')
plt.gca().yaxis.set_major_locator(tck.MultipleLocator(5))
plt.show()

For your data I got the following plot:

enter image description here

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41