频率分布图:将x轴更改为间隔

问题描述 投票:1回答:1

互联网亲爱的人们

我已经计算出频率分布,现在我想以某种方式绘制它。到目前为止,我已经计算并绘制了频率分布,但是找不到我要寻找的最终产品的解决方案。我现在带有示例数据集的代码是:

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

# example data
rng = np.random.RandomState(seed=12345)
a1 = stats.norm.rvs(size=1000, random_state=rng)
res = stats.relfreq(a1, numbins=34)
x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, res.frequency.size)

# plotting
fig = plt.figure(figsize=(6, 3))
ax = fig.add_subplot(1, 1, 1)
ax.bar(x, res.frequency, width=res.binsize)
ax.set_title('Frequency Distribution of 1D Vix Returns')
ax.set_xlim([x.min(), x.max()])
ax.set_xticks(ax.get_xticks()[::1])
plt.show()

作为最后一步,我想像附图中那样绘制x轴。我希望使用间隔而不是单个数字。我找不到解决此问题的消息来源。有没有人遇到过同样的问题,或者知道有什么解决方案?在此先感谢

enter image description here

python plot distribution frequency
1个回答
1
投票

看看这个不错的答案:https://stackoverflow.com/a/6353051/10372616

我已将代码添加到您当前的绘图中。

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

# example data
rng = np.random.RandomState(seed=12345)
a1 = stats.norm.rvs(size=1000, random_state=rng)
res = stats.relfreq(a1, numbins=34)
x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, res.frequency.size)

# plotting
fig = plt.figure(figsize=(6, 3))
ax = fig.add_subplot(1, 1, 1)
ax.bar(x, res.frequency, width=res.binsize)
ax.set_title('Frequency Distribution of 1D Vix Returns')
ax.set_xlim([x.min(), x.max()])
ax.set_xticks(ax.get_xticks()[::1])

# Change traditional tick labels to range labels
# ----------------------------------------------------------------
ax.set_xticklabels([]) # hide your previous x tick labels
bins = ax.get_xticks()[::1]
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for a, b, x in zip(bins, bins[1:], bin_centers):
    label = '{:0.0f} to {:0.0f}'.format(a, b)
    ax.annotate(label, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -10), textcoords='offset points', va='top', ha='center', rotation=90)

plt.show()

之前:before

之后:after

© www.soinside.com 2019 - 2024. All rights reserved.