[PYTHON] Change the Y-axis scale of Matplotlib to exponential notation (10 Nth power notation)

ex1) Draw a graph

test1.py



import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt

#SQLAlchemy initialization
CONNECT_INFO = 'mssql+pyodbc://hogehoge'
engine = sqlalchemy.create_engine(CONNECT_INFO, encoding='utf-8')

#Variable setting
qq = 1
ym = 201607

#DB connection, stored execution, pandas data frame creation
query = 'EXEC dbo.sp_rtrv_hogehoge @q = {0},@prd = {1}'.format(qq,ym )
df = pd.read_sql_query(query, engine  ,index_col =['t'])

#Graph drawing
ax = df.plot(  color=('b','r') , alpha=0.6  )
plt.title('hogehoge_title')
plt.grid(which='major')
#ax = plt.gca()

#Save file
fname ='test'+ str(ym) +'.png'
plt.savefig(fname) 
plt.close()  

-Plot () of pandas (df) is a wrapper method of plt.plot () of matplotlib. -In the above, the SQLSevrer stored procedure is executed (in SQL Server, the stored procedure is executed by EXEC). -Stored arguments (qq and ym) are specified in python variable embedded notation. -You can get the graph currently being edited with ʻax = plt.gca () `

-In the above, no Y-axis scale is applied, so for example, in the case of 1 million, it is written as "1000000" as it is.

Y-axis scale ↓ ex1.png

ex2) Change the Y-axis scale to scientific notation

test1.py



import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt

#(Omission)

#Graph drawing
ax = df.plot(  color=('b','r') , alpha=0.6  )
#ax = plt.gca()
ax.ticklabel_format(style="sci",  axis="y",scilimits=(0,0))

Y-axis scale ↓ ex2.png

・ It became a scale like "Data Scientist" (laughs) However, with the notation of le6, there is a risk that the boss of the liberal arts Osan, who is weak in mecha, will become a boon (white eyes), so the next ex3 was fine-tuned.

ex3) Change the Y-axis scale to a power of 10 notation

test1.py



import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

#(Omission)

#Graph drawing
ax = df.plot(  color=('b','r') , alpha=0.6  )
#ax = plt.gca()
ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.ticklabel_format(style="sci",  axis="y",scilimits=(0,0))

-If you set the property of ScalarFormatter to ʻuseMathText = True`, it becomes a power notation of 10. ・ One million is $ 1 × 10 ^ 6 $ (** 10 to the 6th power **, that is, 6 zeros)

Y-axis scale ↓ ex3.png

ex4) Change the Y-axis scale from 1 × 10 ^ 6 to 1 × 10 ^ 4.

test4.py



import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

#Class settings * Inherit ScalarFormatter
class FixedOrderFormatter(ScalarFormatter):
    def __init__(self, order_of_mag=0, useOffset=True, useMathText=True):
        self._order_of_mag = order_of_mag
        ScalarFormatter.__init__(self, useOffset=useOffset, 
                                 useMathText=useMathText)
    def _set_orderOfMagnitude(self, range):
        self.orderOfMagnitude = self._order_of_mag

#(Omission)

#Graph drawing
ax = df.plot(  color=('b','r') , alpha=0.6  )
#ax = plt.gca()
ax.yaxis.set_major_formatter(FixedOrderFormatter(4 ,useMathText=True))
#ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.ticklabel_format(style="sci",  axis="y",scilimits=(0,0))

・ Depending on the data, you may want to use 10,000 units ($ 1 x 10 ^ 4 ) instead of 1 million notation ( 1 x 10 ^ 6 $)! ・ When I searched and searched various things such as matplotlib's github and stackOverflow, it seems that ScalarFormatter has an orderOfMagnitude, and here it controls the N part of 10 Nth power. -In the above, the class that inherits ScalarFormatter is set, and the state of ʻuseMathText = True` is kept as it is, and the orderOfMagnitude of ScalarFormatter is specified and changed to 10 4 notation.

Y-axis scale ↓ ex4.png

・ 10,000 is $ 1 × 10 ^ 4 $ (** 10 to the 4th power **, that is, 4 zeros), so 1 million is $ 100 × 10 ^ 4 $

Reference URL

[Matplotlib] I want to use the scale of the axis as exponential notation (via. · Matplotlib: format axis offset-values to whole numbers or specific numbers (Via.stackOverflow) ・ Github: matplotlib / lib / matplotlib / ticker.py

Recommended Posts

Change the Y-axis scale of Matplotlib to exponential notation (10 Nth power notation)
Change the style of matplotlib
Script to change the description of fasta
About the X-axis notation of Matplotlib bar graphs
Change the decimal point of logging from, to.
Add information to the bottom of the figure with Matplotlib
Omit the decimal point of the graph scale in matplotlib
[Introduction to Python] Basic usage of the library matplotlib
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
An introduction to object orientation-let's change the internal state of an object
Change the volume of Pepper according to the surrounding environment (sound)
The road to download Matplotlib
Change the theme of Jupyter
The Power of Pandas: Python
How to change the log level of Azure SDK for Python
How to change the color of just the button pressed in Tkinter
Feel free to change the label of the legend in Seaborn in python
[Go] Create a CLI command to change the extension of the image
I summarized how to change the boot parameters of GRUB and GRUB2
Change the Flyweight pattern to Pythonic (?) (2)
Change the background of Ubuntu (GNOME)
Change the Python version of Homebrew
Power the brushless motor of Oriental motor
The power of combinatorial optimization solvers
Change the Flyweight pattern to Pythonic (?) (1)
Change the suffix of django-filter / DateFromToRangeFilter
Unravel the mystery of matplotlib specgram
About the size of matplotlib points
Supplement to the explanation of vscode
[Python] Change the alphabet to numbers
I want to change the color by clicking the scatter point in matplotlib
When you want to change the HTTP headers of Flask's test client