Issue
I generate two plots in seaborn which share y-axis. I'm wondering how I can make the shared y-axis labels center-aligned. I am looking for some ideas and improvements. The plot is attached.
import seaborn as sns
import matplotlib.pylab as plt
import numpy as np
import string
import random
labels = []
for i in range(10):
labels.append(''.join(random.choices(string.ascii_lowercase, k=4)))
labels.append(''.join(random.choices(string.ascii_lowercase, k=7)))
score = np.abs(np.random.randn(20))
fig, axes = plt.subplots(1,2 , figsize=(5,5 ), sharey=True )
for ii in range(2):
ti = sns.barplot(y=[j for j in range(len(score))],x=score, ax=axes[ii],
orient='h' )
ti.set_yticklabels(labels)
if ii ==0:
ti.invert_xaxis()
ti.yaxis.tick_right()
fig.tight_layout(w_pad=0, pad=1)
plt.show()
Solution
The ti.set_yticklabels(labels)
has options to align horizontally using ha
, multi-align text with ma
. I have made use of ha and adjusted using the position
argument as well. It seems to be aligned. Probably this could also help to design and play with it to get to right format. Reference here (Look at other parameters)
Below is the updated code snippet for the part of the changes only:
for ii in range(2):
ti = sns.barplot(y=[j for j in range(len(score))],x=score, ax=axes[ii],
orient='h')
ti.set_yticklabels(labels, ha="center", position=(1.2,0)) # ha and position adjustments.
if ii ==0:
ti.invert_xaxis()
ti.yaxis.tick_right()
plt.tight_layout(w_pad=0, pad=2.5) # Some padding adjustments.
plt.show()
Finally the output looks like this:
Answered By - coldy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.