pceccon
pceccon

Reputation: 9844

Set commom xticks (string) for subplots using Matplotlib

Given a set of subplots, I'd like to set common xticks labels for them. I know how to do that when the ticks are numerical:

cmap = plt.get_cmap('Set3')
colors = [cmap(i) for i in numpy.linspace(0, 1, 18)]

data_1 = numpy.random.rand(18, 7)
data_2 = numpy.random.rand(18, 7)
data_3 = numpy.random.rand(18, 7)
data_4 = numpy.random.rand(18, 7)

y = range(365)
plt.figure(figsize=(15,7))
for i in range(18):
    plt.plot(y, data_1[i, :], color=colors[i], linewidth=2)
    plt.plot(y, data_2[i, :], color=colors[i], linewidth=2)
    plt.plot(y, data_3[i, :], color=colors[i], linewidth=2)
    plt.plot(y, data_4[i, :], color=colors[i], linewidth=2)
plt.setp(axes, xticks=range(7))
plt.tight_layout()

enter image description here

However, now I'd like my ticks label to be strings. Given that, I tried something like this:

plt.setp(axes, xticks=(range(12), ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']))

But it doesn't work:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thank you.

Upvotes: 0

Views: 822

Answers (1)

DavidG
DavidG

Reputation: 25380

You can manually set strings on your xticks as shown in the example below:

x = [1,2,3,4,5,6,7,8,9,10,11,12]
y = [1,2,3,4,5,6,7,8,9,10,11,12]

plt.plot(x,y)
my_xticks = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

plt.xticks(x, my_xticks)
plt.show()

Upvotes: 1

Related Questions