【问题标题】:How to arrange years of x-axis in matplotlib如何在 matplotlib 中排列 x 轴的年份
【发布时间】:2021-09-14 14:30:14
【问题描述】:

我在 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()

【问题讨论】:

  • “减少年限”是什么意思?
  • 是的比如1872 - 1875 - 1880 ...这样可以让x轴更加空间和清晰。

标签: python pandas numpy matplotlib seaborn


【解决方案1】:

生成一些样本数据:

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))
})

要以 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()


或者将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()

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2021-11-20
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多