简体   繁体   中英

How to scale histogram y-axis in million in matplotlib

I am plotting a histogram using matplotlib but my y-axis range is in the millions. How can I scale the y-axis so that instead of printing 5000000 it will print 5

Here is my code

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

filename = './norstar10readlength.csv'
df=pd.read_csv(filename, sep=',',header=None)

n, bins, patches = plt.hist(x=df.values, bins=10, color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()

And here is the plot I am generating now

l

An elegant solution is to apply a FuncFormatter to format y labels.

Instead of your source data, I used the following DataFrame :

       Val
0   800000
1  2600000
2  6700000
3  1400000
4  1700000
5  1600000

and made a bar plot. "Ordinary" bar plot:

df.Val.plot.bar(rot=0, width=0.75);

yields a picture with original values on the y axis ( 1000000 to 7000000 ).

But if you run:

from matplotlib.ticker import FuncFormatter

def lblFormat(n, pos):
    return str(int(n / 1e6))

lblFormatter = FuncFormatter(lblFormat)
ax = df.Val.plot.bar(rot=0, width=0.75)
ax.yaxis.set_major_formatter(lblFormatter)

then y axis labels are integers (the number of millions):

在此处输入图像描述

So you can arrange your code something like this:

n, bins, patches = plt.hist(x=df.values, ...)
#
# Other drawing actions, up to "plt.ylim" (including)
#
ax = plt.gca()
ax.yaxis.set_major_formatter(lblFormatter)
plt.show()

You can modify your df itself, you just need to decide one ratio so if you want to make 50000 to 5 then it means the ratio is 5/50000 which is 0.0001

Once you have the ratio just multiply all the values of y-axis with the ratio in your DataFrame itself.

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM