简体   繁体   English

如何在matplotlib中排列x轴的年数

[英]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)我在 python 中有一个如下的箱线图 - matplotlib,有人可以帮助我减少 x 轴上的年间距(下图)

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:要以 5 年为间隔设置年份,请获取unique “YearBuilt”列并使用np.where设置year % 5为 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 :或者将tick locator设置为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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