简体   繁体   中英

How to remove numerical x-ticks under custom labels in matplotlib's boxplot?

I want to plot multiple boxplots (using matplotlib in python3) into one figure and label them accordingly along the x axis. I have tried multiple methods to set custom x-ticks, but the old, numerical ticks always show through.

The following two code snippets yield the same result. In the first one, I use plt.xticks(ticks, labels, rotation='vertical') to set the ticks (also does not work wo rotation). In both cases compressed_runs is a dict, where the keys coincide with the x-ticks' labels and the values are numeric arrays.

plt.figure(figsize=[10, 8], dpi=300)
labels = ['test']*len(compressed_runs)
ticks = [i+1 for i, v in enumerate(compressed_runs)]

plt.xticks(ticks, labels, rotation='vertical')
plt.ylabel('communication times [µs]')
plt.title('Test title')

plt.boxplot(compressed_runs.values(), showfliers=False)
plt.savefig(plotname)
plt.close()

I also tried modifying the figure's axes directly:

fig = plt.figure(figsize=[10, 8], dpi=300)
labels = ['test']*len(compressed_runs)
ticks = [i+1 for i, v in enumerate(compressed_runs)]

plt.xticks(ticks, labels, rotation='vertical')
fig.axes[0].set_xticklabels(labels)
plt.ylabel('communication times [µs]')
plt.title('Test title')

plt.boxplot(compressed_runs.values(), showfliers=False)
plt.savefig(plotname)
plt.close()

模糊的 x-ticks

As you can see in the figure, the enumerated x-ticks still show through from underneath the named x-ticks. In this case I expect only 'test' to be under each boxplot.

The problem turned out to be the order of function calls. plt.xticks(ticks, labels) should be called after creating the boxplot, not before. The numerical ticks were the boxplot's default behavior, which was printed onto the labels that were explicitly set before. In the working code I then had:

plt.boxplot(compressed_runs.values(), showfliers=False)
plt.xticks(ticks, labels, rotation='vertical')

instead of

plt.xticks(ticks, labels, rotation='vertical')
plt.boxplot(compressed_runs.values(), showfliers=False)

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