Johnny Tam
Johnny Tam

Reputation: 495

Categorical axis labels instead of numbers for box plot?

I would like to generate a horizontal boxplot with cmap color filling of the boxes and I found this: How can I set boxplot color by rainbow in matplotlib

I modified the code so to include categories at index like this:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
import numpy as np

# Random test data
test_data_df = pd.DataFrame([np.random.normal(mean, 1, 10) for mean in range(10)])
index = ["a","b","c","d","e","f","g","h","i","j"]
test_data_df.index = index

fig, axes = plt.subplots(figsize=(5, 5))

# Horizontal box plot
bplot = axes.boxplot(test_data_df,
                     vert=False,   # vertical box aligmnent
                     patch_artist=True)   # fill with color

# Fill with colors
cmap = cm.ScalarMappable(cmap='nipy_spectral')
test_mean = [np.mean(x) for x in test_data]
for patch, color in zip(bplot['boxes'], cmap.to_rgba(test_mean)):
    patch.set_facecolor(color)

plt.show()

enter image description here

How could I modify the code to use the index ["a","b","c","d","e","f","g","h","i","j"] as the y-axis label?

Thanks!

Upvotes: 1

Views: 1208

Answers (1)

tdy
tdy

Reputation: 41327

As commented, you can set_yticklabels to your index list:

axes.set_yticklabels(index)

box plot with categorical axis labels

Upvotes: 1

Related Questions