如何使MatplotlibPandas条形图看起来像历史图?

如何使MatplotlibPandas条形图看起来像历史图?,第1张

如何使Matplotlib / Pandas条形图看起来像历史图? 条形图差异

要获得

bar
类似于该
hist
图的图,需要对的默认行为进行一些处理
bar

  1. bar
    通过传递x(
    hist.index
    )和y(
    hist.values
    )强制使用实际x数据绘制范围。默认
    bar
    行为是在任意范围内绘制y数据,并将x数据作为标签。
  2. width
    参数设置为与x数据的实际步长相关(默认值为
    0.8
  3. align
    参数设置为
    'center'
  4. 手动设置轴图例。

需要这些变化经由到制成

matplotlib
bar()
呼吁轴线(
ax
)代替
pandas
bar()
呼吁数据(
hist
)。

绘图示例
%matplotlib inlineimport numpy as npimport pandas as pdimport scipy.stats as statsimport matplotlibmatplotlib.rcParams['figure.figsize'] = (12.0, 8.0)matplotlib.style.use('ggplot')# Setup size and distributionsize = 50000distribution = stats.norm()# Create random datarv = pd.Series(distribution.rvs(size=size))# Get sane start and end points of distributionstart = distribution.ppf(0.01)end = distribution.ppf(0.99)# Build PDF and turn into pandas Seriesx = np.linspace(start, end, size)y = distribution.pdf(x)pdf = pd.Series(y, x)# Get histogram of random datay, x = np.histogram(rv, bins=50, normed=True)# Correct bin edge placementx = [(a+x[i+1])/2.0 for i,a in enumerate(x[0:-1])]hist = pd.Series(y, x)# Plot previously histogrammed dataax = pdf.plot(lw=2, label='PDF', legend=True)w = abs(hist.index[1]) - abs(hist.index[0])ax.bar(hist.index, hist.values, width=w, alpha=0.5, align='center')ax.legend(['PDF', 'Random Samples'])



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4897970.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存