Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

python - How to divide y-axis (to change units) AND change format (no decimals)

I would like to plot a DataFrame with a different unit than the one of my dataset (without changing the df or copying).

So I divide by 1000 following the advice in this post

ax.yaxis.set_major_formatter(yfmt)

Then, I would like to delete the decimals, so I use this line of code:

import matplotlib.ticker as tkr
ax.yaxis.set_major_formatter(tkr.StrMethodFormatter('{x:,.0f}'))

However, I can't get both. My y-axis is divided by 1000 or without decimals, but not both formats.

Any idea? In advance, thanks for your help!

question from:https://stackoverflow.com/questions/65672102/how-to-divide-y-axis-to-change-units-and-change-format-no-decimals

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of retrospectively modifying the labels, you should change directly the formatter function:

from matplotlib import pyplot as plt
import matplotlib.ticker as tkr  


def numfmt(x, pos):
    s = f'{x/1000:,.0f}' #<----
    return s

yfmt = tkr.FuncFormatter(numfmt)
 
#sample data
import pandas as pd
df = pd.DataFrame({"cat": list("ABCDE"), "xaxis": [1, 3, 4, 5, 9], "yaxis": [1236, 3213, 2123, 6243, 1432]})

fig, ax = plt.subplots()
ax.plot(df.xaxis, df.yaxis)
ax.yaxis.set_major_formatter(yfmt)
plt.show()

Sample output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...