简体   繁体   中英

How to arrange years of x-axis in matplotlib

I have a box-plot as below in python - matplotlib, could anybody help me to reduce years' spacing in x-axis (attached picture below)

fig, ax = plt.subplots(figsize = (16,8))

data = pd.concat([df_train.SalePrice, df_train.YearBuilt],axis=1)

sns.boxplot('YearBuilt','SalePrice',data=data)

plt.xticks(rotation=90)

plt.show()

箱线图

Generate Some Sample Data:

import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

# Generate Some Sample Data
np.random.seed(15)
dr = np.repeat(pd.date_range('1872-01-01', '2011-01-01', freq='Y').year, 10)
data = pd.DataFrame({
    'YearBuilt': dr,
    'SalePrice': np.random.randint(0, 70_000, len(dr))
})

To set years at 5 year intervals get the unique 'YearBuilt' Columns and use np.where to set ticks where year % 5 is 0:

fig, ax = plt.subplots(figsize=(16, 8))
sns.boxplot(x='YearBuilt', y='SalePrice', data=data, ax=ax)
years = np.sort(data['YearBuilt'].unique())
ax.set_xticklabels(np.where(years % 5 == 0, years, ''))
plt.xticks(rotation=90)
plt.show()

阴谋


Alternatively set the tick locator to a MultipleLocator :

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import seaborn as sns

# Generate Some Sample Data
np.random.seed(15)
dr = np.repeat(pd.date_range('1872-01-01', '2011-01-01', freq='Y').year, 10)
data = pd.DataFrame({
    'YearBuilt': dr,
    'SalePrice': np.random.randint(0, 70_000, len(dr))
})
fig, ax = plt.subplots(figsize=(16, 8))
sns.boxplot(x='YearBuilt', y='SalePrice', data=data, ax=ax)

ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))
plt.xticks(rotation=90)
plt.show()

情节 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM