【问题标题】:plot log-scale and linear scale functions and histograms on same canvas在同一画布上绘制对数刻度和线性刻度函数和直方图
【发布时间】:2016-10-28 14:00:31
【问题描述】:

我有一个概率密度函数,我只能评估对数而不会遇到数字问题。我有一个直方图,我想在同一个画布上绘制。但是,对于直方图,我需要选项log=True 将其绘制为对数刻度,而对于函数,我只能直接获得值的对数。如何在同一画布上绘制两者?

请查看此 MWE 以说明问题:

import matplotlib.pyplot as plt
import random
import math
import numpy as np

sqrt2pi = math.sqrt(2*math.pi)
def gauss(l):
  return [ 1/sqrt2pi * math.exp(-x*x) for x in l]
def loggauss(l):
  return [ -math.log(sqrt2pi) -x*x for x in l ]

# just fill a histogram
h = [ random.gauss(0,1) for x in range(0,1000) ]
plt.hist(h,bins=21,normed=True,log=True)

# this works nicely 
xvals = np.arange(-4,4,0.1)
plt.plot(xvals,gauss(xvals),"-k")
# but I would like to plot this on the same canvas:
# plt.plot(xvals,loggauss(xvals),"-r")

plt.show()

有什么建议吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果我理解正确,您想在同一个图中,在同一个 x 轴上绘制两个数据集,但一个在对数 y 尺度上,一个在线性 y 尺度上。您可以使用twinx

    fig, ax = plt.subplots()
    ax.hist(h,bins=21,normed=True,log=True)
    ax2 = ax.twinx()
    ax2.plot(xvals, loggauss(xvals), '-r')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多