python - 在 Pandas 中使用 Dataframe.plot 时如何更改每个子图的 bin 大小
问题描述
我有一个包含所有数字列的 DataFrame,其中列之间的数据范围差异很大。下面的代码提供了一个有代表性的例子:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'A': np.random.randn(10000) * 20,
'B': np.random.randn(10000) * 1000,
'C': np.random.randn(10000) * 0.01,
'D': np.random.randn(10000) * 300000,
'E': np.random.randn(10000) * 500
})
axs = df.plot(kind = 'hist',subplots = True, bins = 10, layout = (2,3), figsize = (12,8), title = list(df.columns), sharex = False, sharey = True)
for i, ax in enumerate(axs.reshape(-1)):
if i>= len(df.columns):
break
ax.set_xlim(df[df.columns[i]].min(),df[df.columns[i]].max())
plt.suptitle('Histograms for all features')
plt.tight_layout()
plt.show()
当df.plot
被调用时,xlim 范围被自动设置为具有最大数字的列的范围,这就是为什么我添加了for循环来解决这个问题。
但是,正如您在下面的屏幕截图中看到的那样,bin 没有正确缩放。
我希望每个子图都显示 10 个 bin,每个 bin 的宽度适合每个直方图。有没有办法做到这一点,无论是调用df.plot
还是使用某种方法访问 Axes 对象?
解决方案
您可以改用 pandas hist 函数。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'A': np.random.randn(10000) * 20,
'B': np.random.randn(10000) * 1000,
'C': np.random.randn(10000) * 0.01,
'D': np.random.randn(10000) * 300000,
'E': np.random.randn(10000) * 500
})
df.describe()
plt.figure();
df.hist(bins = 10,layout = (2,3),density = True, figsize = (12,8), sharex = False, sharey = False
);
推荐阅读
- ruby-on-rails - rails collection_check_boxes 标签未显示
- jquery - 使用 Jquery 从多个选择选项中获取自定义属性值
- python - 无法存储来自 aws rekognition 响应的数据
- r - 根据另一个列表中的值选择列表中的小标题列
- java - 将链接更改为可在 TextView 上点击的自定义字符串
- c# - 在 vs2017 中运行自定义工具时出现 T4 错误
- android - 从风味自动启动android代码而不覆盖Application.onCreate
- flutter - 我如何在颤动的尾随属性内添加更多 2 个按钮和 1 个文本
- r - data.table 评估 1/0 不等于 TRUE/FALSE
- node.js - NOT NULL 约束因批量插入而失败