简体   繁体   中英

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. However, I want to adjust the x-ticks so that the span the entire x-axis at regular intervals. 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. 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

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 .

Optionally, you can also explicitly set a locator and a formatter , for example the MultipleLocator and the ScalarFormatter . Note that in this case the twinx() axis doesn't add any value, but just complicates matters.

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

示例图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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