【问题标题】:Matplotlib logarithmic x-axis and paddingMatplotlib 对数 x 轴和填充
【发布时间】:2017-02-24 18:50:02
【问题描述】:

我在 matplotlib 和 x 轴上的填充以及对数刻度上苦苦挣扎(见第一张图片)。 如果没有对数刻度,则填充效果很好(参见第二个)。 任何建议如何在绘图线和左下角的轴线之间获得填充,以便人们可以看到线上的点?

谢谢。

代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import *
from matplotlib.ticker import ScalarFormatter

style.use('fivethirtyeight')

fig, ax = plt.subplots()

T = np.array([2**x for x in range(0,7+1)])
opt1 = np.array([x for x in range(0,7+1)])
opt2 = np.array([x*2 for x in range(0,7+1)])
opt3 = np.array([x*4 for x in range(0,7+1)])

ax.grid(True) 
xlabel("#nodes")
ylabel("time(s)")
legend(loc="best") 
title(r"Node start times") 

plt.xticks([2**x for x in range(0,7+1)])

plt.plot(T,opt1,"o-", label="opt1")
plt.plot(T,opt2, "s-", label="opt2")
plt.plot(T,opt3, "d-", label="opt2")
plt.legend(loc="upper left")
# This should be called after all axes have been added
plt.tight_layout()
plt.margins(0.05, 0.05)
# 1, 2, 4, ...
ax.set_xscale('log', basex=2)
ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%d"))
plt.show()
#savefig("plot_1.pdf")

【问题讨论】:

  • 请注意:您可以将opt1opt2、...写成np.arange(8)np.arange(0,15,2)、...以避免Python循环。

标签: python matplotlib padding


【解决方案1】:

这不能解决您的填充问题,但您可以使用clip_on=False 来防止点被切断。看来您还需要使用zorder 确保它们在轴上方

plt.plot(T,opt1,"o-", label="opt1", clip_on=False, zorder=10)
plt.plot(T,opt2, "s-", label="opt2", clip_on=False, zorder=10)
plt.plot(T,opt3, "d-", label="opt2", clip_on=False, zorder=10)

【讨论】:

  • 看起来比以前好多了