2017-01-24 41 views
1

我想做一个特殊的x-ticks标签,我试图在下面的照片中进行说明。 enter image description here在matplotlib中设置x个刻度区域

你知道该怎么做吗?

编辑:我目前的代码最低版本:

import matplotlib.pyplot as plt 


xvalues = [ 0., 1., 1., 1., 1., 2., 2., 2., 2., 2., 
    2., 3., 3., 3., 3., 4.] 
yvalues = [ 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 
    0., 0., 0., 0., 0., 0.] 

tx = [0] * len(xvalues) 
for i in range(len(xvalues)): 
    tx[i] = i 

newxvalues = xvalues 

seen = set() 
newxvalues = [x if x not in seen and not seen.add(x) else '' for x in newxvalues ] 
newxvalues[0] = ' ' 
plt.plot(tx, yvalues, color='g', linewidth=1.5) 
plt.xlim([-1, len(xvalues)]) 
plt.xticks(tx, newxvalues, rotation="90") 
plt.ylim(-0.03, 1.1) 
plt.tick_params(axis='x', top='off', bottom='off') 
plt.show() 

enter image description here

EDIT2:我不需要花哨的括号,如果它简化了问题。例如方括号也没关系

+0

也许你可以编辑清晰度的问题。 – Lucas

回答

1

这是可能的。以下代码提供了一个类AxesDecorator,您需要在脚本结尾处调用该类。它需要一个应该改变标签标记的轴实例,以及应该绘制的刻度。 它假设所有的蜱都是平分的。

import matplotlib.pyplot as plt 
import numpy as np 
from mpl_toolkits.axes_grid1 import make_axes_locatable 

class AxesDecorator(): 
    def __init__(self, ax, size="5%", pad=0.05, ticks=[1,2,3], spacing=0.05, 
       color="k"): 
     self.divider= make_axes_locatable(ax) 
     self.ax = self.divider.new_vertical(size=size, pad=pad, sharex=ax, pack_start=True) 
     ax.figure.add_axes(self.ax) 
     self.ticks=np.array(ticks) 
     self.d = np.mean(np.diff(ticks)) 
     self.spacing = spacing 
     self.get_curve() 
     self.color=color 
     for x0 in ticks: 
      self.plot_curve(x0) 
     self.ax.set_yticks([]) 
     plt.setp(ax.get_xticklabels(), visible=False) 
     self.ax.tick_params(axis='x', which=u'both',length=0) 
     ax.tick_params(axis='x', which=u'both',length=0) 
     for direction in ["left", "right", "bottom", "top"]: 
      self.ax.spines[direction].set_visible(False) 
     self.ax.set_xlabel(ax.get_xlabel()) 
     ax.set_xlabel("") 
     self.ax.set_xticks(self.ticks) 

    def plot_curve(self, x0): 
     x = np.linspace(x0-self.d/2.*(1-self.spacing),x0+self.d/2.*(1-self.spacing), 50) 
     self.ax.plot(x, self.curve, c=self.color) 

    def get_curve(self): 
     lx = np.linspace(-np.pi/2.+0.05, np.pi/2.-0.05, 25) 
     tan = np.tan(lx)*10 
     self.curve = np.hstack((tan[::-1],tan)) 
     return self.curve 


# Do your normal plotting  
fig, ax = plt.subplots() 

x = [1,2,3,4,5] 
y = [4,5,1,3,7] 
ax.scatter(x,y, s=900, c=y,) 
ax.set_ylim([0,10]) 
ax.set_xlabel("Strange axis") 

#at the end call the AxesDecorator class 
# with the axes as argument 
AxesDecorator(ax, ticks=x) 

plt.show() 

enter image description here

+0

这个ansatz看起来很有前途。不幸的是,间距不同。如果我发布我的代码,它会有帮助吗? – HighwayJohn

+0

进行了编辑。希望它有帮助 – HighwayJohn

+0

如果这可以简化问题,我不需要花哨的括号。例如方括号也可以。 – HighwayJohn