【问题标题】:xticks on only bin ticksxticks 仅在 bin 刻度上
【发布时间】:2020-09-24 00:00:37
【问题描述】:

我有一个包含日期时间数据的数据框,它的列显示不同假期有多少天。我想创建该数据的直方图,并尝试了以下代码:

holiday_features = [name for name in df.columns if 'DAYS FROM' in name]
for feature in holiday_features:
    plt.hist(df[feature], bins=12)
    plt.title(feature)
    plt.xticks(rotation=60)
    plt.show()

当我创建该循环时,出现如下直方图:

刻度似乎代表了每一个特征,而不仅仅是垃圾箱。将直方图放大到淫秽的比例证实了这一点:

我只对 bin 刻度感兴趣,而不是功能刻度。如何删除这些刻度以制作更整洁的直方图?

【问题讨论】:

  • 看起来您正在为同一个 matplotlib 图上的每个特征绘制直方图。在拨打hist 之前尝试添加plt.figure()。要了解如何设置自定义xticks,您可以参考 SO 上的许多示例,例如this
  • @JacoSolari 我明白你在说什么,但我只提供了该系列的第一个。所有的直方图看起来都像这个。关于这个特定问题,plt.show() 实际上有效地打破了循环,因此直方图不会全部叠加。

标签: python matplotlib histogram xticks


【解决方案1】:

我的建议是使用subplots,并在Axes类上操作xticks。

例如,对于单个图:

_, axis = plt.subplots(1, 1) # create an Axes class for a single plot
axis.hist(data, bins=12)
axis.set_xticklabels(axis.get_xticks(), rotation=60)
plt.show()

上面的代码产生了一个具有以下美感的图:

此外,考虑到在您的情况下,您正在绘制许多特征,您可以使用 subplots 函数生成一个绘图网格,如下所示:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns

holiday_features = [name for name in df.columns if 'DAYS FROM' in name]

# define number of rows and columns to the subplot
ncols = 3  # considering a grid with 3 plots per row
nrows = int(np.ceil(len(holiday_features)/3))

# create subplots
_, axes = plt.subplots(nrows, ncols)
axes = axes.flatten()

# plot features with rotated ticks
for j, feature in enumerate(holiday_features):
    axes[j].hist(df[feature], bins=12)
    axes[j].set_title(feature)
    axes[j].set_xticklabels(axes[j].get_xticks(), rotation=60)
    
# remove empty plots
for k in range(j, len(axes)):
    sns.despine(ax=axes[k], top=True, right=True, left=True, bottom=True)
    axes[k].xaxis.set_major_formatter(ticker.NullFormatter())
    axes[k].xaxis.set_ticks_position('none')
    axes[k].yaxis.set_major_formatter(ticker.NullFormatter())
    axes[k].yaxis.set_ticks_position('none')

# show plot
plt.tight_layout()
plt.show()

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 2022-08-04
    • 2023-03-28
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多