- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想可视化数学域或区间。同样,我想可视化一个 bool 数组。有多个这样的阵列,理想情况下,它们一个一个地绘制在另一个上方。
我拥有的是一些数据:多段录音,比如 100 分钟。每个记录仅在部分时间满足给定条件。我想形象化每个录音都是“真实”的时间。一些更简单的变体:
在我的例子中,每个记录都可以是多个间隔的并集。例如:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
sb.set_context("paper")
times = np.arange(0, 100)
mask1 = (times >= 0) * (times <= 30) + (times >= 70) * (times <= 100)
mask2 = (times >= 20) * (times <= 80)
我可以用我写的这两个函数分别绘制每个记录:
def bool2extreme(mask, times) :
"""return xmins and xmaxs for intervals in times"""
binary = 1*mask
slope = np.diff(binary)
extr = (slope != 0)
signs = slope[extr]
mins = list(times[1:][slope==1])
maxs = list(times[:-1][slope==-1])
if signs[0]==-1:
mins = [times[0]] + mins
if signs[-1]==1:
maxs = maxs + [times[-1]]
return mins, maxs
def plot_interval(mask, times, y=0, color='k', ax=None) :
if ax==None:
print('None')
ax = plt.gca()
xmins, xmaxs = bool2extreme(mask, times)
for xmin, xmax in zip(xmins, xmaxs):
ax.plot([xmin, xmax], [y,y], lw=6, color=color)
return ax
我的问题是控制各个间隔之间的垂直间距。事实上,当我绘制其中一个时,有一个我不想要的垂直轴。即使我将它的可见性设置为 False,它仍然存在并占用空间。因此,当我将每个记录放在不同的子图中时,它们之间的垂直间距太大了:
masks = [mask1, mask2]
labels = ['domain1', 'domain2']
n_plots = len(masks)
fig, axs = plt.subplots(n_plots, sharex=True)
for i, mask in enumerate(masks) :
axs[i] = plot_interval(mask, times, ax=axs[i])
axs[-1].set_xlabel('Time (min)')
sb.despine()
我尝试过的另一种选择是:将所有间隔都放在同一个轴上,但 y 值不同。但是间隔之间的垂直间距问题仍然存在。
masks = [mask1, mask2]
labels = ['domain1', 'domain2']
n_plots = len(masks)
fig, ax = plt.subplots(sharex=True)
for i, mask in enumerate(masks) :
ax = plot_interval(mask, times, y=i, ax=ax)
ax.set_xlabel('Time (min)')
ax.set_yticks(range(n_plots))
ax.set_yticklabels(labels)
ax.grid(axis="x")
sb.despine(left=True)
如何控制这些间隔之间的垂直间距?
最佳答案
一些想法:
height/num_axes
分开ax.yaxis.set_visible(False)
隐藏 y 轴上的刻度ax.spines['left'].set_color('None')
使 y 轴的脊椎不可见ax.spines['bottom'].set_position(('data', 0))
将 x 轴放置在 y=0
高度<ax.tick_params(labelbottom=True)
为所有子图中的 xtick 设置标签(而不是仅在最后一个)(-1.5,.5)
,因此可以适本地选择厚度;下面有更多空间为 xticks 的标签腾出空间ax.tick_params(which='both', direction='in')
获取上方而不是下方的刻度线(主要刻度和次要刻度)要在左侧添加标签,以下方法对我有用:
# ax.yaxis.set_visible(False) # removed, as it also hides the ylabel
ax.set_ylabel('my ylabel', rotation=0, ha='right', labelpad=10)
ax.set_yticks([]) # to remove the ticks, the spine was already removed
在演示代码中,在末尾添加了更多的 xticks 和某种类型的箭头。演示中有 7 个掩码,以更好地查看轴之间的距离效果。尝试让轴尽可能靠近,0.4 英寸的距离似乎是可行的。 (bool2extreme
函数未受影响,因为它与用作输入的格式密切相关。)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Polygon
import matplotlib.ticker as plticker
import seaborn as sbs
sbs.set_context("paper")
times = np.arange(0, 101)
num_masks = 7
masks = [np.zeros_like(times, dtype=bool) for _ in range(num_masks)]
for i in range(num_masks):
for j in range(50):
masks[i] += (times >= (i+3)*j) * (times <= (i+3)*j+i+1)
masks = masks[::-1] # reverse to get the masks plotted from bottom to top
def bool2extreme(mask, times) :
"""return xmins and xmaxs for intervals in times"""
binary = 1*mask
slope = np.diff(binary)
extr = (slope != 0)
signs = slope[extr]
mins = list(times[1:][slope==1])
maxs = list(times[:-1][slope==-1])
if signs[0]==-1:
mins = [times[0]] + mins
if signs[-1]==1:
maxs = maxs + [times[-1]]
return mins, maxs
def plot_interval(mask, times, xlim=None, y=0, thickness=0.4, color='k', ax=None):
if ax is None:
ax = plt.gca()
ax.yaxis.set_visible(False)
ax.spines['left'].set_color('None')
ax.spines['right'].set_color('None')
ax.spines['top'].set_color('None')
ax.spines['bottom'].set_position(('data', 0))
ax.tick_params(labelbottom=True) # to get tick labels on all axes
# ax.tick_params(which='both', direction='in')` # tick marks above instead below the axis
ax.xaxis.set_major_locator(plticker.MultipleLocator(base=10)) # major ticks in steps of 10
ax.xaxis.set_minor_locator(plticker.MultipleLocator(base=1)) # minor ticks in steps of 1
ax.set_ylim(-1.5,.5)
if xlim is None:
xlim = (times[0]-0.9, times[-1]+0.9)
ax.set_xlim(xlim)
xmins, xmaxs = bool2extreme(mask, times)
for xmin, xmax in zip(xmins, xmaxs):
#ax.add_patch(Rectangle((xmin, y-thickness), xmax-xmin, 2*thickness, linewidth=0, color=color))
ax.add_patch(Rectangle((xmin, y), xmax-xmin, thickness, linewidth=0, color=color))
triangle1 = [(xlim[0]-0.5, y), (xlim[0], y-thickness), (xlim[0], y+thickness)]
ax.add_patch(Polygon(triangle1, linewidth=0, color='black', clip_on=False))
triangle2 = [(xlim[1]+0.5, y), (xlim[1], y-thickness), (xlim[1], y+thickness)]
ax.add_patch(Polygon(triangle2, linewidth=0, color='black', clip_on=False))
return ax
n_plots = len(masks)
dist_between_axis_in_inches = 0.4
fig, axs = plt.subplots(n_plots, sharex=True, figsize=(10, dist_between_axis_in_inches*len(masks)))
for i, mask in enumerate(masks) :
axs[i] = plot_interval(mask, times, xlim=(times[0]-0.5, times[-1]+0.5), ax=axs[i], color='lime')
axs[-1].set_xlabel('Time (min)')
plt.show()
轴靠近的结果:
附言:This post包含更多关于添加箭头的建议。
关于python - 如何创建多个一维轴,用彩色线条显示间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494501/
我有一个 Haskell 程序,它用 Metropolis 模拟 Ising 模型 算法。主要操作是一个模板操作,它需要下一个的总和 2D 中的邻居,然后将其与中心元素相乘。那么 元素可能已更新。 在
对于卷积,我想在一个维度上应用圆形填充,在所有其他维度上应用零填充。我该怎么做? 对于卷积,有 28 个 channel ,并且数据在球形箱中描述。半径时间有 20 个箱子,极地时间有 20 个箱子,
假设您有一个数组并想创建另一个数组,该数组的值连续等于第一个数组的 10 个元素的标准差。在 for 循环的帮助下,它可以像下面的代码一样轻松编写。我想要做的是避免使用 for 循环来加快执行时间。有
我有一个长度为size * size的一维数组,表示值的平方字段。 我的目标是将数组旋转到位(previous question)。我目前在获取正确的内圈索引方面遇到问题。我的算法有什么错误? 这是我
stride = 1 和 1 个过滤器的 1D CNN 的输出长度不应该等于输入长度而不需要填充吗? 我认为是这种情况,但创建了一个具有这些规范的 Keras 模型,当输入形状为 (17910,1)
我有一个零散布的一维数组。想创建第二个数组,其中包含最后一个零的位置,如下所示: >>> a = np.array([1, 0, 3, 2, 0, 3, 5, 8, 0, 7, 12]) >>> fo
我试着去理解卡尔曼滤波器是如何工作的,因为多维变量太混乱了,一开始我从一维的例子开始。 我发现有3个不同的来源解释温度计的情况,但所有这些情况实现的方程略有不同,我没有得到重点。 我实现了解决方案2,
我有一个二维数组,我需要将它转换为一个列表(同一对象)。我不想使用 for 或 foreach 循环来执行此操作,它们将获取每个元素并将其添加到列表中。还有其他方法吗? 最佳答案 好吧,你可以让它使用
我正在使用 Keras 构建一个 CNN,将以下 Conv1D 作为我的第一层: cnn.add(Conv1D( filters=512, kernel_size=3, str
在 Python 中使用 TensorFlow,我正在制作一个以一维数组作为输入的神经网络。我想在网络中添加一个卷积层,但似乎无法让它工作。 我的训练数据如下所示: n_samples = 20 le
我有一个简单的一维数组,但我想使用 jQuery 将长列表分成两列。我怎样才能实现这个目标? var articles = ['article10','article9','article8','ar
我有一个刚从文件中读入的 float 的一维 vector 。 std::vector result(s.size() / sizeof(float)); 我想像这样使用这些数据 myTable[rl
使用 numpy 将 data reshape 为 fencepost 的最有效方法是什么? data = np.array([1, 2, 3, 4, 5])
我正在尝试通过删除 for 循环并仅在处理大型数据集时使用 numpy 数组来优化一些代码。 我想采用一维 numpy 数组,例如: a = [1, 2, 3, 4, 5] 并生成一个 2D nump
我正在尝试为两个数组 Pages 和 Price 赋值。 #include int main() { static int pages[3]; static int price[3];
我是深度学习、keras API 和卷积网络的新手,如果这些错误是幼稚的,请事先致歉。我正在尝试构建一个用于分类的简单卷积神经网络。输入数据 X 有 286 个样本,每个样本有 500 个时间点,4
假设我有 Numpy 数组 p 和一个 Scipy 稀疏矩阵 q 这样 >>> p.shape (10,) >>> q.shape (10,100) 我想做 p 和 q 的点积。当我尝试使用 nump
我需要一些行为类似于 std::vector 的东西(界面/功能/等)但我需要它是平坦的,即它不能动态分配缓冲区。显然,这通常不起作用,因为可用大小必须在编译时确定。但我希望类型能够处理N没有额外分配
作为我正在运行的一些模拟的一部分,我需要最终对一些非常长的(实数)数字序列执行以下操作。这是要点: 给定一个长的一维 NumPy 数组,对于数组中的每个位置,我想对该位置前后的值进行平均,取平均值之间
这个问题在这里已经有了答案: Concatenating two one-dimensional NumPy arrays (6 个答案) 关闭 5 年前。 我想将 numpy 数组存储到另一个 n
我是一名优秀的程序员,十分优秀!