Bocephus85
Bocephus85

Reputation: 75

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!!!!

Upvotes: 4

Views: 1581

Answers (1)

JohanC
JohanC

Reputation: 80534

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

example plot

Upvotes: 1

Related Questions