将负xticks缩放到不同于正x刻度的刻度

时间:2018-03-28 18:58:49

标签: python matplotlib

这可能吗?

我有一个条形图,表示两个数据帧列之间的差异除以原始数据帧列

        difference = (df - full_df)/full_df 

然后我绘制差异

    difference.plot(kind='barh',color =  ['r' if x > 0 else 'b' for x in difference.values]).\
        set_yticklabels([str(tick)[:45] for tick in difference.index])
    plt.xticks(fontsize=20)
    plt.gca().set_title('Selected minus full feature set averages divided by full', fontsize=30)
    axs[1].yaxis.tick_right()
    axs[1].yaxis.grid(color='gray', linestyle='dashed')
    axs[1].xaxis.grid(color='gray', linestyle='dashed')
    plt.yticks(fontsize=23)        
    plt.tight_layout()

大多数正x数将在0 <0的范围内。 x&lt; 10.所有负数应在-1之间。 x&lt;有没有办法将xtick间隔设置为低于零.1(或类似的东西)和xtick间隔高于0到1,所以x轴看起来像:

 [-1,-.9,-.8,-.7,-.6,-.5,-.4,-.3,-.2,-.1,0,1,2,3,4,5,6,7,8,9, to inf] ? 

1 个答案:

答案 0 :(得分:0)

我可能无法正确理解你的问题,但我认为正在寻找一个负x和正x在不同尺度上的情节,但占用的空间相同。我认为最简单的解决方案是缩放x负轴数据,使其与y轴数据吻合良好,然后重新标记原始刻度上的刻度。

import matplotlib.pyplot as plt
import numpy as np

# original data
x = [-1,-.9,-.8,-.7,-.6,-.5,-.4,-.3,-.2,-.1,0,1,2,3,4,5,6,7,8,9,]
y = range(len(data_x))

# scale negative x values
x_mod =[i*10 if i < 0 else i for i in x]

# draw plots  
with sns.axes_style('whitegrid'):
    fig, ax = plt.subplots(2,1,figsize=(5,8))

    # unscaled
    ax1 = ax[0]
    ax2 = ax[1]
    ax1.plot(data_x, data_y)
    ax1.vlines(0, 0, 20, color='black') # mark x = 0 
    ax1.set_title('unscaled data')

    # scaled
    ax2.plot(x_mod, data_y)

    # fix the xticks and their labeling
    xticks = list(np.concatenate([np.arange(-1,0, 0.2),np.arange(0,11,2)]))
    xtick_locs  = list(np.concatenate([np.arange(-1,0, 0.2) *10, np.arange(0,11,2)]))

    ax2.set(xticks=xtick_locs, xticklabels = xticks)
    ax2.vlines(0, 0, 20, color='black')
    ax2.set_title('scaled data')

enter image description here