python - 如何使 pyplot 均匀分布 y 刻度值 [0, 1/2, 3/4, 7/8, ...]

标签 python matplotlib plot axis

我想通过收敛概率曲线图比较几种算法。

目前,我的图表如下所示:

enter image description here

这不允许看到许多曲线的差异。

我希望 y Axis 为“对数”,但与值 1 不同,即我希望 y 值为 [0, 1/2, 3/4, 7/8, 15/16 , ... 1023/1024], 但因此每个刻度与最后一个刻度的距离仍然相同(即,从 1/2 到 3/4 的距离与从 15/16 到 31/32 的距离相同) .

我试过使用 yticks() 函数,但它没有均匀放置刻度:

enter image description here

How do I make this axis look right?


我当前的代码:

def plotCDFs(CDFs, names = []):
   legend = []
   for i, CDF in enumerate(CDFs):
       keys = sorted(CDF)
       vals = sorted(CDF.values())
       plt.plot(keys,vals)
       legend.append(str(names[i]))
   plt.title('Cumulative Distribution')
   plt.legend(legend, loc='lower right')
   plt.xscale('log')
   plt.gca().set_ylim([0,1])
   #plt.yticks([1-2**-i for i in xrange(11)])
   plt.show()

最佳答案

有两种可能性:您可以在普通的对数对数图中绘制1-cumulative Distribution,这是我通常做的,或者您(可能)必须创建自己的对数图如上所述。至少我从未见过实现此目的的内置函数。

这段代码应该可以工作

import numpy as np
import matplotlib.pyplot as plt

def ToLog(x):
    return 1.-np.log10(1.-x)

def plotCDFs(CDFs, names = []):
    legend = []
    max_vals = 0.0
    for i, CDF in enumerate(CDFs):
        keys = sorted(CDF)
        vals = sorted(CDF.values())
        if vals.max() > max_vals:
            max_vals = vals
        plt.plot(keys,ToLog(vals))
        legend.append(str(names[i]))
    plt.title('Cumulative Distribution')
    plt.legend(legend, loc='lower right')
    plt.xscale('log')

    # handling the yaxis ticks and ticklabels
    i_max = np.floor(np.log(1-max_vals.max())/np.log(2.))
    yticks = 1.-2.**np.linspace(i_max,0,-i_max+1)
    ax = plt.gca()
    ax.set_yticks(1.-np.log10(1.-yticks))
    ax.set_yticklabels([str(i-1)+'/'+str(i) for i in 2**np.arange(-int(i_max),0,-1)])

    ax.set_ylim([0,1])
    plt.show()

请注意,在绘图之前,必须将 ToLog 应用于所有 ydata

关于python - 如何使 pyplot 均匀分布 y 刻度值 [0, 1/2, 3/4, 7/8, ...],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933571/

相关文章:

python - django,基于位置的搜索

python - 为什么我的 Python 函数在调用我的函数后会创建 None 类型?

r - 如何在多个未分组的图中保持恒定的文本大小和 x 轴比例

python - Matplotlib 没有给出错误,但没有绘制任何内容

r - 使用 Plotly 和 R 的悬停模式

python - 使用 Opencv 检测图像中的文本区域

Python 3.5 async/await 与真实代码示例

python - Tkinter 无法正确关闭并启动新文件

python - 绘制窄范围数据的奇数指数

python - 如何左对齐饼图?