简体   繁体   English

如何使用正确的 X-ticks 将 (x,y) 图叠加到 Python 中的箱线图上?

[英]How Do I Overlay a (x,y) Plot onto a Boxplot in Python with Correct X-ticks?

I am trying to combine a box plot with a line plot.我正在尝试将箱线图与线图结合起来。 I am able to get both different plot types to appear on the same figure together and have the boxplots be at the correct x-locations.我能够让两种不同的绘图类型一起出现在同一个图形上,并使箱线图位于正确的 x 位置。 However, I want to adjust the x-ticks so that the span the entire x-axis at regular intervals.但是,我想调整 x 刻度,以便以固定间隔跨越整个 x 轴。 I am not having any luck using xlim and xticks to change the tick locations -- I think the box plot is messing things up there.我没有任何运气使用 xlim 和 xticks 来更改刻度位置 - 我认为箱线图在那里搞砸了。 I've tried overlaying plots separately, but I'm still not having any luck.我试过分别叠加图,但我仍然没有任何运气。 Below you can see the code I'm trying to implement to overlay the two plots.下面你可以看到我试图实现的代码来覆盖两个图。

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()

which, with the data on hand, creates the following image: overlayed xy-plot and boxplot使用手头的数据,创建以下图像:叠加的 xy-plot 和 boxplot

Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks!!!!谢谢!!!!

Default, the boxplot changes the tick positions as well as with the labels and their format.默认情况下,箱线图会更改刻度位置以及标签及其格式。 You can suppress this via the parameter manage_ticks=False .您可以通过参数manage_ticks=False来抑制这一点。

Optionally, you can also explicitly set a locator and a formatter , for example the MultipleLocator and the ScalarFormatter .或者,您还可以显式设置locator 和 formatter ,例如MultipleLocatorScalarFormatter Note that in this case the twinx() axis doesn't add any value, but just complicates matters.请注意,在这种情况下, 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()

示例图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM