Vitalii Shchudlo
Vitalii Shchudlo

Reputation: 23

How to format the y-axis in matplotlib so it's not an exponential

I am creating graph, and get next result:

enter image description here

How to fix this bad numbering and 1e6 above?

Why is it like this?

I tried using the solution to this prevent scientific notation in matplotlib.pyplot, but it didn't work.

My code:

import matplotlib.pyplot as plt
plt.title(f'TOP 10 videos by {choice}')
plt.xlabel('TOP places')
plt.ylabel(f'Number')

labels_top = ['Top10', 'Top9', 'Top8', 'Top7', 'Top6', 'Top5', 'Top4', 'Top3', 'Top2', 'Top1']
y_count = [50235, 90312, 150123, 250000, 290134, 370241, 385153, 768512, 955025, 1255531]

for graph in range(len(y_count[:10])):
    plt.bar(labels_top.pop(), y_count.pop())
    
plt.gca().ticklabel_format(style='plain')

I got this error:

Traceback (most recent call last):
  File "/home/vitalii/PycharmProjects/mediagroupukraine_test_task/venv/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 3130, in ticklabel_format
    axis.major.formatter.set_scientific(is_sci_style)
AttributeError: 'StrCategoryFormatter' object has no attribute 'set_scientific'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "app.py", line 41, in <module>
    start()
  File "app.py", line 37, in start
    app(channel_name, channel_id)
  File "app.py", line 27, in app
    menu_graphs()
  File "app.py", line 25, in menu_graphs
    show_statistic_graph(formatted_data_for_graphs, menu_choice)
  File "/home/vitalii/PycharmProjects/mediagroupukraine_test_task/graphs.py", line 48, in show_statistic_graph
    plt.gca().ticklabel_format(style='plain')
  File "/home/vitalii/PycharmProjects/mediagroupukraine_test_task/venv/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 3140, in ticklabel_format
    raise AttributeError(
AttributeError: This method only works with the ScalarFormatter

Upvotes: 1

Views: 3752

Answers (1)

Zephyr
Zephyr

Reputation: 12496

You need to pass to matplotlib.axes.Axes.ticklabel_format which axis you want to format, in your case only y axis, so:

plt.gca().ticklabel_format(axis='y', style='plain')

Since you are not passing axis parameter to ticklabel_format, it uses default value, so both. In this way matplotlib is trying to format with style = 'plain' x axis too, but this is not feasible, so you get the AttributeError.

Upvotes: 3

Related Questions