【问题标题】:Log scale for multiple subplot histograms in pandas大熊猫中多个子图直方图的对数比例
【发布时间】:2020-11-11 17:38:15
【问题描述】:

我正在尝试使用 matplotlib 中的轴方法 set_yscale() 在每个直方图的 y 轴上生成对数刻度,但是当使用 @ 中的 by 键创建多个直方图时,它似乎忽略了此方法987654324@.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# generate some random data
df = pd.DataFrame(np.random.randint(0,100,size=(1000, 2)), columns=list('AB'))


fig, ax = plt.subplots(figsize = (15,20))
ax.set_yscale('log')
df['A'].hist(ax=ax, by=df['B'])

【问题讨论】:

  • 你如何使用一个元组来解包不同子图的轴? fig, (ax1, ax2) = plt.subplot(1, 2)matplotlib.org/3.3.2/api/_as_gen/…
  • @Robert 似乎确实有效,但如果您有几十个子图,它就不是一个可扩展的解决方案。
  • 你能提前指定你想要的subplot的形状吗? fig, axs = plt.subplots(4, 1) 然后您可以在一个列表理解中设置比例:[ax.set_yscale('log') for ax in axs]

标签: python python-3.x pandas matplotlib


【解决方案1】:

您的代码会产生一个警告,指出ax 将被删除并替换为新的坐标区实例。现在,这很好,但你的地块在不同的轴上,而不是原来的轴上。所以你需要处理这些:

# no need to initiate `fig,ax` to avoid the warning
axes = df['A'].hist(by=df['B'], figsize=(10,15))

# set log scale
for a in axes.ravel(): a.set_yscale('log')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2020-04-02
    • 2018-07-05
    • 2015-01-25
    相关资源
    最近更新 更多