如何强制和编辑pyplot子图的主要和次要日志图记号

2024-09-30 14:36:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在绘制数据时,我希望能够控制子地块的主刻度和次刻度。然而,无论我尝试什么,我似乎都无法修改我的第二个子批的滴答声。我尝试过应用其他stackoverflow问题的建议,但不幸的是没有用。我认为我在构建箱线图时犯了一些根本错误

由于我的同事中没有人对matplotlib有太多的经验,所以我要向你们求助!任何帮助都将不胜感激

目前,我的数据如下:

Example Plot

在第二个箱线图上,我还希望每隔10^X强制一个主刻度,并显示默认的日志次刻度

目前,我生成的箱线图如下所示:

def generateLogBoxPlot(title, plot_id, xlabels, data, initializion_time, fig):

    # Create an axes instance
    ax = fig.add_subplot(plot_id)

    # Set Log Scale
    ax.set_yscale('log')

    # Create the boxplot
    bp = ax.boxplot(data_of_plot)

    # Show Initialization Time (as a Line)
    line = plt.plot(...)

    # Custom rotated x-axis labels
    ax.set_xticklabels(xlabels)
    plt.xticks(rotation=15)

    #Set Labels
    plt.ylabel('Time (ms)')
    ax.set_title(title)

    #Show Grid
    ax.get_yaxis().grid()

我这样称呼这个函数:

# Create a figure instance
fig = plt.figure(1, figsize=(9, 3))

# Generate first subplot
generateLogBoxPlot("No Context-Dependent A.C.\nBusiness Case", #title 
121, #plot_id
["Add User", "Add Role", "Add Demarcation", "Add Permission"], #labels
results["AddEntities"], #data
40000, #initializion_time
fig) #figure 

line = generateLogBoxPlot("Context-Dependent A.C.\nBusiness Case", 
122, #plot_id
["Add User", "Add Role", "Add Demarcation", "Add Permission"], #labels
results["AddEntities2"], #data
153000, #initialization_time
fig) #figure

#Show Legend
plt.legend(plt.plot([], [],linestyle="--", color="#A9A9A9", label="Initialization 
Time"),["Initialization Time"], loc='center left', bbox_to_anchor=(1, 0.5))

#Show
plt.tight_layout()
plt.show()

无论我尝试什么,我似乎只能修改fist子地块的滴答声。如何在第二个子地块上强制/编辑它们


Tags: addiddatatimeplottitleshowfig
1条回答
网友
1楼 · 发布于 2024-09-30 14:36:10

Matplotlib根据值的范围以及在某种程度上的地物大小,自动显示或隐藏对数刻度的小刻度。关于y轴基准10对数刻度,以下是我在测试下面所示示例的变化时注意到的内容(使用matplotlib 3.3.2和默认设置):

  • 对于4英寸(默认)或更高的地物高度:当y轴的范围包括9个整数倍或更大时,对数刻度将从在每个整数倍和所有次刻度上显示带有标签的主刻度切换到在没有次刻度的情况下每两个(或更多)幂整数显示一个主刻度(如右侧的绘图)
  • 对于小于4英寸的图形高度(这似乎是您的情况):可以根据y轴的范围和可用空间更灵活地调整刻度

对于您的特定示例,在任何情况下,我都会从共享y轴开始,以使绘图更具可比性。然后剩下两个选项:要么保留默认的记号格式,不使用小记号,要么强制两个绘图都使用小记号

matplotlib默认日志勾选行为的示例以及如何更改它

首先,以下是带有日志标记的matplotlib默认行为的示例:

import numpy as np                 # v 1.19.2
import matplotlib.pyplot as plt    # v 3.3.2
import matplotlib.ticker as ticker

# Create sample data with exponentially increasing values for x and
# the y functions and where the y functions are nearly identical
x = 10**np.linspace(0, 3, 30)
y1 = x**2
y2 = x**2.5

# Create figure and subplots containing semilogy plots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3))
fig.suptitle('Matplotlib defaults with figure height of 3 inches', y=1.25)

ax1.set_title('Minor ticks are shown\n\n', pad=10)
ax1.semilogy(x, y1, label='y1')
ax1.legend(loc='lower right')

ax2.set_title(f'Minor ticks are not shown:\nthe y range covers less than 9 \
integer\npowers, but the figure height is <4 inches', pad=10)
ax2.semilogy(x, y2, label='y2')
ax2.legend(loc='lower right')

plt.show()

mpl_logticks1


现在,如果图形高度增加,为刻度留出更多空间,该怎么办

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
fig.suptitle('Figure height of 4 inches', y=1.15)

ax1.set_title('Minor ticks are not shown:\nthe custom y-axis limits causes the\
\ny range to cover 9 integer powers', pad=10)
ax1.semilogy(x, y1, label='y1')
ax1.legend(loc='lower right')
ax1.set_ylim(1, 10**8) # the minor ticks disappear by changing the axis limits

ax2.set_title('Minor ticks are shown by default:\nthe y range covers less \
than 9 integer\npowers and the figure height is 4 inches', pad=10)
ax2.semilogy(x, y2, label='y2')
ax2.legend(loc='lower right')

plt.show()

mpl_logticks2

这个特殊的例子表明,增加图形大小可以解决小刻度不显示的问题,但情况往往并非如此

下面是如何通过使用来自^{}模块的^{}强制显示小刻度,无论y的范围和图形大小如何(此示例还包括共享的y轴):

# Add sharey=True
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3), sharey=True)
fig.suptitle('Figure height of 3 inches with\ncustomized tick locator and shared \
y-axis', y=1.25)

ax1.set_title('Ticks shared by ax2\n', pad=10)
ax1.semilogy(x, y1, label='y1')
ax1.legend(loc='lower right')

ax2.set_title('Customized LogLocator:\nminor ticks are forced to be shown', pad=10)
ax2.semilogy(x, y2, label='y2')
ax2.legend(loc='lower right')

# Set ax2 major and minor tick locators with custom parameters to show
# all major and minor ticks despite the small figure height and the large
# range of y: the numticks argument must be an arbitrary number at least
# one unit above the number of integer powers covering the range of y
nticks = 9
maj_loc = ticker.LogLocator(numticks=nticks)
min_loc = ticker.LogLocator(subs='all', numticks=nticks)
ax2.yaxis.set_major_locator(maj_loc)
ax2.yaxis.set_minor_locator(min_loc)

# The tick labels are formatted as one would expect, so no need to use
# log tick formatters for this example.

plt.show()

mpl_logticks

如果要创建始终显示任何值范围的小刻度的绘图函数,则需要将numticks设置为高值



参考文献:answer by ImportanceOfBeingErnestmatplotlib Log Demomatplotlib Tick Locators

相关问题 更多 >