【问题标题】:Plotting 2D Histogram with customize bins values in Python在 Python 中使用自定义 bin 值绘制 2D 直方图
【发布时间】:2020-06-21 11:43:45
【问题描述】:

我有以下包含数千行的 pandas 数据框。

我想根据“mains:active_power”和“mains:reactive_power”绘制一个二维直方图。 我使用 matplotlib 库在 Python 中绘制 2D 直方图:

import matplotlib.pyplot as plt
fig = plt.subplots(figsize =(10, 7)) 
plt.hist2d(df["mains:active_power"], df["mains:reactive_power"]) 
plt.title("Simple 2D Histogram")  
plt.show()

绘图成功,但我想自定义 x_bin 和 y_bin 的 bin 值。 我为此使用了以下命令:

plt.hist2d(df["mains:active_power"], df["mains:reactive_power"], bins =[x_bins, y_bins]).

x_bins, y_bins 是包含 bin 值的 NumPy 数组。另外,x_bins、y_bins的大小等于dataframe的长度(df)

每当我运行此程序时,都会出现错误:

ValueError: bins[0] 必须是单调递增的,当数组时

如何解决这个问题?

谢谢:)

【问题讨论】:

  • 您好,请告诉大家您是如何解决的或接受答案,以便将来的人知道如何解决这个问题。
  • 为什么x_bins, y_bins的大小等于数据帧的长度?

标签: python pandas dataframe matplotlib


【解决方案1】:

我认为 plt.bar 会是一个更好的选择。

width = bins[1] - bins[0]
plt.bar(bins, hist, align="edge", width=width)
plt.show()

希望我能帮上忙。在这里提出了同样的问题以供进一步参考。 bins must increase monotonically

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多