Austin
Austin

Reputation: 7349

Bigger x-axis range in seaborn plot

I'm plotting a bar graph with matplotlib/seaborn and the range is the min/max values, plus it skips values that have 0 counts. How can I both pad the range and not skip 0 values?

# bar
ax2 = figDayMonth.add_subplot(2,1,2)
ax2 = sns.countplot(x=np.asarray(dayMonth), palette="pastel")
ax2.set_title('Days of Month Counts', FontSize=20)
ax2.tick_params(labelsize=15)
ax2.set_ylabel("Count", FontSize=16)
ax2.set_xlabel("Day of Month", FontSize=16)
sns.despine(left=True, bottom=True, top=True, right=True)
plt.show()
print(2*'\n')

enter image description here

dayMonth is a list of integers with the above counts. Although for example there are no 2, 29, or 30 values, I'd still like the graph to reserve a place for those values.

I tried ax2.set_xticks(np.arange(32)) but that just seems to squeeze my graph to the left without changing the x-axis values.

Upvotes: 0

Views: 2701

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339705

Essentially you want to plot a histogram of the input list. That histogram can be created using

x = np.arange(1,33)
plt.hist(dayMonth, bins=x)

A full example would be

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

dayMonth = [1,3,12,30,2,3,12,16,18,31,3,13,16,18,30,1,3,12,16,18,30]
x = np.arange(1,33)    
_,_,bars = plt.hist(dayMonth, bins=x, align="left")

colors=sns.color_palette(palette="pastel", n_colors=len(x))
for color, bar in zip(colors, bars):
    bar.set_color(color)
plt.gca().set_xlim(-1,32)
plt.xticks(x[:-1])
plt.show()

enter image description here

Upvotes: 1

Related Questions