简体   繁体   中英

Change Y axis tick scale with log bar graph python

I have a bar graph that is log scaled that I am trying to change the y ticks from 10^1, 10^2, etc., to whole numbers. I have tried setting the tick values manually, and tried setting the values from the data, and also setting the format to scalar. One thing I notice in all of the questions I am looking at is that my construction of the graph doesn't include subplot .

def confirmed_cases():
    x = df['Date']
    y = df['Confirmed']
    plt.figure(figsize=(20, 10))
    plt.bar(x, y)
    plt.yscale('log')
#     plt.yticks([0, 100000, 250000, 500000, 750000, 1000000, 1250000])
#     plt.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    plt.title('US Corona Cases By Date')
    plt.xlabel('Date')
    plt.ylabel('Confirmed Cases')
    plt.xticks(rotation=90)

在此处输入图像描述

There a few issues:

  • The formatter needs to be placed at the yaxis of the ax . Use plt.gca() to get the current ax . Note that there is no function plt.get_yaxis() .
  • The scalar formatter starts using exponential notation for large numbers. To prevent that, set_powerlimits((m,n)) makes sure the powers are only shown for values outside the range 10**m and 10**n .
  • In a log scale, major ticks are used for values 10**n for integer n . The other ticks or minor ticks, at positions k*10**n for k from 2 to 9. If there are only a few major ticks visible, the minor ticks can also get a tick label. To suppress both the minor tick marks and their optional labels, a NullFormatter can be used.
  • Avoid using a tick at zero for a log-scale axis. Log(0) is minus infinity.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib

plt.figure(figsize=(20, 10))
plt.bar(np.arange(100), np.random.geometric(1/500000, 100))
plt.yscale('log')
formatter = matplotlib.ticker.ScalarFormatter()
formatter.set_powerlimits((-6,9))
plt.gca().yaxis.set_major_formatter(formatter)
plt.gca().yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
plt.yticks([100000, 250000, 500000, 750000, 1000000, 1250000])
plt.show()

结果图

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