我有要在直方图中绘制的数据(DFE)

Nr        O18ad
0        -4.268475
1        -4.265793
2        -4.263120
3        -4.260457
4        -4.257803
            ...
359995   -7.813345
359996   -7.821394
359997   -7.773479
359998   -7.807605
359999   -7.797769

这里我有这个代码片段:它是一个8部分图形的一部分,因此使用SUBFIGN函数

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

def plot_Diff(data):
    fig = plt.figure(figsize=(10, 10))
    ax =fig.add_subplot(423)  
    x= dfe['O18ad']
    bins=[-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
    old_yticks = ax.get_yticks()
    bin_counts, _, bars = plt.hist(x, bins,  alpha=0.65, label='old', edgecolor='black', color='lightgrey')
    new_max_tick = bin_counts.max()
    old_yticks = ax.get_yticks()
    new_ticks =  old_yticks[old_yticks < new_max_tick][:-1]
    new_ticks = np.append(new_ticks, new_max_tick)
    ax.set_yticks(new_ticks)
    manual_ticks=[0,20_000]
    if manual_ticks is None:
        old_yticks = ax.get_yticks()
        new_ticks = old_yticks[old_yticks < new_max_tick][:-1] 
        new_ticks = np.append(new_ticks, new_max_tick)
    else:
        new_ticks = np.append(manual_ticks, new_max_tick)
    ax.set_yticks(new_ticks)

plt.show()

我的输出如下所示:

enter image description here

现在我的问题是,如何更改X轴刻度,以便在右角自动设置最大值(在本例中为0),在左角自动设置显示的最小值(在本例中为-20)?

自动设置最大值和最小值很重要,因为我有大约100个直方图,我不能总是手动设置它们.

推荐答案

如果我理解正确的话,您想要找到最左边的非空箱的左边,同样在右边.

bins是存储箱边的稀疏数组时,左侧边为bins[:-1](第一条边到倒数第二条边),而右侧边是bins[1:]条(第二条边到最后一条边).因为bin_counts也是一个Numy数组,所以可以用[bin_counts > 0]来索引,以过滤出非空桶.所获得的最小和最大值将作为轴的极限.

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

dfe = pd.DataFrame({'O18ad': np.random.normal(0.01, 0.1, 1000).cumsum()})
dfe['O18ad'] -= dfe['O18ad'].max() + np.random.uniform(0.1, 5)

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
x = dfe['O18ad']
bins = np.arange(-20, 2)
old_yticks = ax.get_yticks()
bin_counts, _, bars = plt.hist(x, bins, alpha=0.65, label='old', edgecolor='black', color='lightgrey')
new_max_tick = bin_counts.max()
print(bins[:-1][bin_counts > 0].min())
print(bins[1:][bin_counts > 0].max())

ax.set_xlim(bins[:-1][bin_counts > 0].min(), bins[1:][bin_counts > 0].max())

plt.show()

using non-empty bins as limits for histogram plot

Python相关问答推荐

如何输入提示抽象方法属性并让mypy高兴?

在for循环中保存和删除收件箱

使用Curses for Python保存和恢复终端窗口内容

在Python中,什么表达相当于0x1.0p-53?

如何将Matplotlib的fig.add_axes本地坐标与我的坐标关联起来?

强制venv在bin而不是收件箱文件夹中创建虚拟环境

有什么方法可以避免使用许多if陈述

拆分pandas列并创建包含这些拆分值计数的新列

使用LineConnection动画1D数据

我从带有langchain的mongoDB中的vector serch获得一个空数组

Pandas 滚动最接近的价值

如何让剧作家等待Python中出现特定cookie(然后返回它)?

通过pandas向每个非空单元格添加子字符串

两个pandas的平均值按元素的结果串接元素.为什么?

Python+线程\TrocessPoolExecutor

将JSON对象转换为Dataframe

Python列表不会在条件while循环中正确随机化'

判断solve_ivp中的事件

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

导入错误:无法导入名称';操作';