Skip to main content
 首页 » 编程设计

python之如何在 pandas 的 DataFrame.plot.hist 中使用不同的轴刻度

2024年10月01日7myhome

我发现 DataFrame.plot.hist 非常方便,但在这种情况下我找不到解决方案。

我想绘制数据集中许多列的分布。问题是 pandas 在所有 x 轴上保持相同的比例,导致大部分图无用。这是我正在使用的代码:

X.plot.hist(subplots=True, layout=(13, 6), figsize=(20, 45), bins=50, sharey=False, sharex=False) 
plt.show() 

这是结果的一部分:

问题似乎在于 pandas 在所有列上使用相同的 bin,而不管它们的值如何。 pandas 中是否有方便的解决方案,还是我被迫手动完成?

我将数据居中(零均值和单位方差),结果有所改善,但仍然不能接受。

请您参考如下方法:

有几个选项,这里是代码和输出:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
 
# Dummy data - value ranges differ a lot between columns 
X = pd.DataFrame() 
for i in range(18): 
    X['COL0{0}'.format(i+38)]=(2**i)*np.random.random(1000) 
 
# Method 1 - just using the hist function to generate each plot 
X.hist(layout=(3, 6), figsize=(20, 10), sharey=False, sharex=False, bins=50) 
plt.title('Method 1') 
plt.show() 
 
# Method 2 - generate each plot separately 
cols = plt.cm.spectral(np.arange(1,255,13)) 
fig, axes = plt.subplots(3,6,figsize=(20,10)) 
for index, column in enumerate(X.columns): 
    ax = axes.flatten()[index] 
    ax.hist(X[column],bins=50, label=column, fc=cols[index]) 
    ax.legend(loc='upper right') 
    ax.set_ylim((0,1.2*ax.get_ylim()[1])) 
fig.suptitle('Method 2') 
fig.show() 

第一个情节:

第二个情节:

我肯定会推荐第二种方法,因为您可以更多地控制各个图,例如,您可以更改坐标轴比例、标签、网格参数和几乎任何其他内容。

我找不到任何可以让您修改原始 plot.hist bins 以接受单独计算的 bins 的东西。

希望对您有所帮助!