如何使用正确的 X 刻度将 (x,y) 图叠加到 Python 中的箱线图上?
How Do I Overlay a (x,y) Plot onto a Boxplot in Python with Correct X-ticks?
我正在尝试将箱线图与线图结合起来。我能够让两种不同的绘图类型一起出现在同一个图形上,并让箱线图位于正确的 x 位置。但是,我想调整 x 刻度,以便定期跨越整个 x 轴。我没有运气使用 xlim 和 xticks 来更改刻度位置——我认为箱线图在那里搞砸了。我试过分别叠加地块,但我仍然没有任何运气。下面你可以看到我试图实现的代码来覆盖两个图。
h = [0.39, 0.48, 0.58, 0.66, 0.78, 0.94]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(h, avg00, '--ko', label='GSE')
ax2.boxplot(phi00, widths=0.05, positions=h, showmeans=True)
ax1.set_xticks(np.arange(0.3, 1.1, 0.1))
ax1.set_xlim(0.3,1.0)
ax1.set_ylim(74,79)
ax2.set_ylim(74,79)
ax2.set_yticks([])
ax1.legend()
plt.show()
根据手头的数据,创建了以下图像:
overlayed xy-plot and boxplot
如有任何帮助,我们将不胜感激。谢谢!!!
默认情况下,箱线图会更改刻度位置以及标签及其格式。您可以通过参数 manage_ticks=False
.
抑制它
您也可以选择显式设置 a locator and a formatter,例如 MultipleLocator
和 ScalarFormatter
。请注意,在这种情况下,twinx()
轴不会增加任何值,只会使事情复杂化。
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, ScalarFormatter
import numpy as np
phi00 = np.random.normal(76.5, 0.7, (20, 6))
avg00 = phi00.mean(axis=0)
h = [0.39, 0.48, 0.58, 0.66, 0.78, 0.94]
fig, ax1 = plt.subplots()
ax1.plot(h, avg00, '--ko', label='GSE')
ax1.boxplot(phi00, widths=0.05, positions=h, showmeans=True, manage_ticks=False)
# ax1.xaxis.set_major_locator(MultipleLocator(0.1))
# ax1.xaxis.set_major_formatter(ScalarFormatter())
ax1.set_xlim(0.3, 1.0)
ax1.set_ylim(74, 79)
ax1.legend()
plt.show()
我正在尝试将箱线图与线图结合起来。我能够让两种不同的绘图类型一起出现在同一个图形上,并让箱线图位于正确的 x 位置。但是,我想调整 x 刻度,以便定期跨越整个 x 轴。我没有运气使用 xlim 和 xticks 来更改刻度位置——我认为箱线图在那里搞砸了。我试过分别叠加地块,但我仍然没有任何运气。下面你可以看到我试图实现的代码来覆盖两个图。
h = [0.39, 0.48, 0.58, 0.66, 0.78, 0.94]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(h, avg00, '--ko', label='GSE')
ax2.boxplot(phi00, widths=0.05, positions=h, showmeans=True)
ax1.set_xticks(np.arange(0.3, 1.1, 0.1))
ax1.set_xlim(0.3,1.0)
ax1.set_ylim(74,79)
ax2.set_ylim(74,79)
ax2.set_yticks([])
ax1.legend()
plt.show()
根据手头的数据,创建了以下图像: overlayed xy-plot and boxplot
如有任何帮助,我们将不胜感激。谢谢!!!
默认情况下,箱线图会更改刻度位置以及标签及其格式。您可以通过参数 manage_ticks=False
.
您也可以选择显式设置 a locator and a formatter,例如 MultipleLocator
和 ScalarFormatter
。请注意,在这种情况下,twinx()
轴不会增加任何值,只会使事情复杂化。
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, ScalarFormatter
import numpy as np
phi00 = np.random.normal(76.5, 0.7, (20, 6))
avg00 = phi00.mean(axis=0)
h = [0.39, 0.48, 0.58, 0.66, 0.78, 0.94]
fig, ax1 = plt.subplots()
ax1.plot(h, avg00, '--ko', label='GSE')
ax1.boxplot(phi00, widths=0.05, positions=h, showmeans=True, manage_ticks=False)
# ax1.xaxis.set_major_locator(MultipleLocator(0.1))
# ax1.xaxis.set_major_formatter(ScalarFormatter())
ax1.set_xlim(0.3, 1.0)
ax1.set_ylim(74, 79)
ax1.legend()
plt.show()