2017-01-24 39 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