在 matplotlib.axes.Axes.set_yscale 中使用 log10 刻度时显示更多次要/主要刻度标签

问题描述 投票:0回答:1
import pandas as pd
from matplotlib import pyplot as plt

## making data
temp_df = pd.DataFrame({'year': [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012],
                        'numbers': [2684044.85, 4005117.02, 3046403.46, 6413495.07, 14885525.21, 5152235.33, 4040850.37,
                                    4616841.13, 4862062.25, 4702041.0, 5201620.42, 4405820.64, 1454650.88]})

## making plot
fig, ax = plt.subplots(figsize=(14,7))
# plot x and y1
ax.plot('year', 'numbers', 'x-', data=temp_df)
ax.set_yscale('log', base=10)

这会产生

y 轴上没有次要刻度标签,通过其他数据,我得到更多主要和次要刻度标签。如何强制在 y 轴上以 log-10 比例动态显示更多刻度标签而不对数字进行硬编码?

我的包版本在 Python 3.10.12 上如下

matplotlib                     3.5.2
matplotlib-inline              0.1.6
pandas                         1.4.4
python matplotlib
1个回答
0
投票

这会抓取当前轴的边界并打开该范围内的小刻度标签。如果主要标签的数量少于三个,它只会打开次要刻度标签。

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


temp_df = pd.DataFrame({
  'year': [2000, 2001, 2002, 2003, 2004, 2005, 2006, 
     2007, 2008, 2009, 2010, 2011, 2012],
  'numbers': [2684044.85, 4005117.02, 3046403.46, 6413495.07, 14885525.21, 
     5152235.33, 4040850.37, 4616841.13, 4862062.25, 4702041.0, 5201620.42, 
     4405820.64, 1454650.88]})

fig, ax = plt.subplots(figsize=(14,7))
ax.set_yscale('log', base=10)
ax.plot('year', 'numbers', 'x-', data=temp_df)
low, high = ax.get_ylim()
ticks = [t for t in ax.get_yticks() if low <= t <= high]

if len(ticks) < 3:
    m_ticker = ticker.LogFormatterSciNotation(
        labelOnlyBase=False, minor_thresholds=(low, high)
    )
    ax.yaxis.set_minor_formatter(m_ticker)
© www.soinside.com 2019 - 2024. All rights reserved.