The Nightman
The Nightman

Reputation: 5759

Seaborn plot not displaying over axis

I have a pandas DataFrame that looks like this:

counts = pd.DataFrame({'Pair A': {8: 4, 9: 1, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0},
 'Pair B': {8: 4, 9: 2, 10: 1, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0},
 'Pair C': {8: 3, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1},
 'Pair D': {8: 2, 9: 1, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0}})

I am just creating a simple plot using part of the DataFrame using the following code:

plt.figure()
sns.set_palette("pastel")
temp = pd.DataFrame(counts).drop([0,1,2,3,4,5,6], axis='index')
temp.index = temp.index + 1

temp.plot()
sns.set_style('ticks')
plt.ylabel('title')
plt.xlabel('xlabel')
plt.title('title')
plt.xticks(range(len(temp.index)), temp.index, rotation=45)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
sns.despine(offset=10, trim=True)
plt.xticks(rotation=45)

But it results in an image that looks like this:

enter image description here

How can I center the plotting over the x-axis?

Upvotes: 0

Views: 1162

Answers (2)

CT Zhu
CT Zhu

Reputation: 54340

When you call plt.xticks, and provide 2 positional arguments, the first argument becomes locs which are the x values where the labels will appear, the second becomes labels which are the tick label values. Therefore with plt.xticks(range(len(temp.index)), temp.index, rotation=45) you are plotting x tick labels at position 0,1,2,3...., while your data are in a different range (8,9,10....).

Therefore if you want to customize your labels, you could change the label part, such as plt.xticks(temp.index, ['x%s'% v for v in temp.index], rotation=45).

Upvotes: 1

The Nightman
The Nightman

Reputation: 5759

It appears that this:

plt.xticks(range(len(temp.index)), temp.index, rotation=45)

causes the problem, and if replaced with this:

plt.xticks(temp.index, temp.index, rotation=45)

everything works as expected.

Upvotes: 0

Related Questions