我想做一个特殊的x-ticks标签,我试图在下面的照片中说明。
你知道怎么做吗?
编辑:我当前代码的最小版本:
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()
Edit2:如果这样可以简化问题,我不需要花哨的括号。例如,方括号也可以
答案 0 :(得分:1)
这是可能的。以下代码提供了一个类AxesDecorator
,您需要在脚本末尾调用它。它需要一个轴实例,应该更改tick标签,以及应该绘制的刻度。
它假定所有刻度均匀分开。
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()