2

I have drawn a countplot as follows:

ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])

(array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]), )

enter image description here

But I want to change the xticks to only show 10, 20, 30, 40 these 4 number, so I checked the documentation and recode it as follows:

ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
plt.xticks(range(10, 41, 10))

enter image description here

But the xticks isn't what I want.
I have searched the relevant questions but I didn't get what I want exactly.
So if not mind could anyone help me?

Bowen Peng
  • 1,635
  • 4
  • 21
  • 39
  • 1
    what about `plt.xticks(range(9, 40, 10), range(10, 41, 10))`? The first range are the x-values of the tick-marks and the second one their labels. – Heike Jun 22 '19 at 07:40
  • @Heike you are right and this works. But if set the range out of the data, it will be a part of blank in the plot. – Bowen Peng Jun 22 '19 at 08:18

1 Answers1

2

One way is to define the labels on the x-axis. The set_xticklabels method from matplotlib module do the job (doc). By defining your own labels, you can hide them by setting the label equal to ''.

By defining your own labels, you need to take care that they are still consistent with your data.

Here is one example:

# import modules
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

#Init seaborn
sns.set()

# Your data to count
y = np.random.randint(0,41,1000)

# Create the new x-axis labels 
x_labels = ['' if i%10 != 0 else str(i) for i in range(len(np.unique(y)))]
print(x_labels)
# ['0', '', '', '', '', '', '', '', '', '', 
# '10', '', '', '', '', '', '', '', '', '', 
# '20', '', '', '', '', '', '', '', '', '', 
# '30', '', '', '', '', '', '', '', '', '', '40']

# Create plot
fig, ax = plt.subplots()
sns.countplot(y)

# Set the new x axis labels
ax.set_xticklabels(x_labels)
# Show graph
plt.show()

enter image description here

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40