- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
tl;dr:在绘制时间序列时如何跳过没有数据的时段?
<小时/>我正在运行一个长时间的计算,我想监控它的进度。有时我会中断这个计算。日志存储在一个巨大的 CSV 文件中,如下所示:
2016-01-03T01:36:30.958199,0,0,0,startup
2016-01-03T01:36:32.363749,10000,0,0,regular
...
2016-01-03T11:12:21.082301,51020000,13402105,5749367,regular
2016-01-03T11:12:29.065687,51030000,13404142,5749367,regular
2016-01-03T11:12:37.657022,51040000,13408882,5749367,regular
2016-01-03T11:12:54.236950,51050000,13412824,5749375,shutdown
2016-01-03T19:02:38.293681,51050000,13412824,5749375,startup
2016-01-03T19:02:49.296161,51060000,13419181,5749377,regular
2016-01-03T19:03:00.547644,51070000,13423127,5749433,regular
2016-01-03T19:03:05.599515,51080000,13427189,5750183,regular
...
实际上,有 41 列。每一列都是一个特定的进度指标。第二列始终以 10000 为步长递增。最后一列是不言自明的。
我想在同一个图表上绘制每一列,同时跳过“关闭”和“启动”之间的时间段。理想情况下,我还想在每个跳跃上画一条垂直线。
<小时/>这是我到目前为止所得到的:
import matplotlib.pyplot as plt
import pandas as pd
# < ... reading my CSV in a Pandas dataframe `df` ... >
fig, ax = plt.subplots()
for col in ['total'] + ['%02d' % i for i in range(40)]:
ax.plot_date(df.index.values, df[col].values, '-')
fig.autofmt_xdate()
plt.show()
我想摆脱那段漫长的平坦期,只画一条垂直线。
我知道df.plot()
,但根据我的经验,它被破坏了(除其他外,Pandas 以自己的格式转换datetime
对象,而不是使用date2num
和 num2date
)。
看起来一个可能的解决方案是编写 custom scaler ,但这看起来相当复杂。
据我了解,编写自定义定位器
只会更改刻度线的位置(小垂直线和相关标签),但不会更改绘图本身的位置。这是正确的吗?
UPD:一个简单的解决方案是更改时间戳(例如,将它们重新计算为“自开始以来耗时”),但我更愿意保留它们。
UPD:答案在https://stackoverflow.com/a/5657491/1214547经过一些修改对我有用。我很快就会写出我的解决方案。
最佳答案
这是一个适合我的解决方案。它不能很好地处理紧密定位的中断(标签可能会变得太拥挤),但就我而言,这并不重要。
import bisect
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.scale as mscale
import matplotlib.transforms as mtransforms
import matplotlib.dates as mdates
import pandas as pd
# heavily borrows from http://stackoverflow.com/a/5657491/1214547
def CustomScaleFactory(breaks):
class CustomScale(mscale.ScaleBase):
name = 'custom'
def __init__(self, axis, **kwargs):
mscale.ScaleBase.__init__(self)
def get_transform(self):
return self.CustomTransform()
def set_default_locators_and_formatters(self, axis):
class HourSkippingLocator(mdates.HourLocator):
_breaks = breaks
def __init__(self, *args, **kwargs):
super(HourSkippingLocator, self).__init__(*args, **kwargs)
def _tick_allowed(self, tick):
for left, right in self._breaks:
if left <= tick <= right:
return False
return True
def __call__(self):
ticks = super(HourSkippingLocator, self).__call__()
ticks = [tick for tick in ticks if self._tick_allowed(tick)]
ticks.extend(right for (left, right) in self._breaks)
return ticks
axis.set_major_locator(HourSkippingLocator(interval=3))
axis.set_major_formatter(mdates.DateFormatter("%h %d, %H:%M"))
class CustomTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
_breaks = breaks
def __init__(self):
mtransforms.Transform.__init__(self)
def transform_non_affine(self, a):
# I have tried to write something smart using np.cumsum(),
# but failed, since it was too complicated to handle the
# transformation for points within breaks.
# On the other hand, these loops are very easily translated
# in plain C.
result = np.empty_like(a)
a_idx = 0
csum = 0
for left, right in self._breaks:
while a_idx < len(a) and a[a_idx] < left:
result[a_idx] = a[a_idx] - csum
a_idx += 1
while a_idx < len(a) and a[a_idx] <= right:
result[a_idx] = left - csum
a_idx += 1
csum += right - left
while a_idx < len(a):
result[a_idx] = a[a_idx] - csum
a_idx += 1
return result
def inverted(self):
return CustomScale.InvertedCustomTransform()
class InvertedCustomTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
_breaks = breaks
def __init__(self):
mtransforms.Transform.__init__(self)
def transform_non_affine(self, a):
# Actually, this transformation isn't exactly invertible.
# It may glue together some points, and there is no way
# to separate them back. This implementation maps both
# points to the *left* side of the break.
diff = np.zeros(len(a))
total_shift = 0
for left, right in self._breaks:
pos = bisect.bisect_right(a, left - total_shift)
if pos >= len(diff):
break
diff[pos] = right - left
total_shift += right - left
return a + diff.cumsum()
def inverted(self):
return CustomScale.CustomTransform()
return CustomScale
# < ... reading my CSV in a Pandas dataframe `df` ... >
startups = np.where(df['kind'] == 'startup')[0]
shutdowns = np.where(df['kind'] == 'shutdown')[0]
breaks_idx = list(zip(shutdowns, startups[1:]))
breaks_dates = [(df.index[l], df.index[r]) for (l, r) in breaks_idx]
breaks = [(mdates.date2num(l), mdates.date2num(r)) for (l, r) in breaks_dates]
fig, ax = plt.subplots()
for col in ['total'] + ['%02d' % i for i in range(40)]:
ax.plot_date(df.index.values, df[col].values, '-')
# shame on matplotlib: there is no way to unregister a scale
mscale.register_scale(CustomScaleFactory(breaks))
ax.set_xscale('custom')
vlines_x = [r for (l, r) in breaks]
vlines_ymin = np.zeros(len(vlines_x))
vlines_ymax = [df.iloc[r]['total'] for (l, r) in breaks_idx]
plt.vlines(vlines_x, vlines_ymin, vlines_ymax, color='darkgrey')
fig.autofmt_xdate()
plt.ticklabel_format(axis='y', style='plain')
plt.show()
关于python - matplotlib:绘制时间序列,同时跳过没有数据的时间段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34580542/
我的算法- private static MyList skip$DeleteItem(MyList L , int M , int N){ MyList curr = L; MyLi
我正在 SWI-Prolog 下开发,但我的目标是 Erlog (https://github.com/rvirding/erlog)。我需要一种使用非标准 Prolog 语法的方法。 有没有办法
我正在尝试从应用程序下载一大堆文件。它的shell命令是“下载文件名”。 我有一个文本文件,其中包含必须下载的所有文件名。我要做的就是运行一个脚本/命令,以便在执行上述命令时 1.从文本文件中提取文件
我试图循环遍历所有用户的评论,但使用 if 语句查找特定值。问题是我的应用程序崩溃了,因为一些用户没有发表评论,因此我得到“无法读取‘收集’未定义的属性”。如何跳过 if 语句的未定义值?代码如下:
我们有按年份分区的索引,例如: items-2019 items-2020 考虑以下数据: POST items-2019/_doc { "@timestamp": "2019-01-01" }
我只是编写一个页面来按实体编号查看每个 ASCII 条目,我想知道是否有一种更简单/更干净的方法来跳过不需要的数字。 var x = new Ar
我希望能够普遍使用重复条目,但也能够跳过特定日期。例子: ** TODO swim practice SCHEDULED 但是,我提前知道 2013-12-25 不会有练习。但是,当我将项目标
如何跳过像这样的 for 循环的一次迭代: for (int i = 65; i <= 90; i++) { if (!(i == 73)) { uniq.add((char) i);
这个问题已经存在: Scanner issue when using nextLine after nextXXX [duplicate] 已关闭 9 年前。 ask=1; while(ask==1)
我在使用一个程序时遇到了一些麻烦,我应该允许用户在程序中输入任意数量的数字,直到他们不再想要为止。然后程序应该计算输入数字的平均值和最大值。我哪里做错了? import java.util.Scann
我有一个名为segments的 Sprite 数组,我想在每个循环中跳过segments的第一个元素。我目前正在这样做: var first = true; for each (var segment
我目前正在编写一个 for 循环来遍历包含 38 个元素的 2D。然而,其中一些元素为空,我希望 for 循环简单地跳过它们(因为在我正在解决的难题中,它们没有与它们相关的移动)。快速搜索表明,我可以
我想使用pre-commit处理我的 git 项目的 git hooks。但是,当我使用它时,git commit 命令不断跳过 unittest 执行: (smartexchange) trnboo
这个问题在这里已经有了答案: Does scanf() take '\n' as input leftover from previous scanf()? (1 个回答) 关闭 9 年前。 我正在
我正在迭代 csv 文件中的每一行,并仅选择/计算满足条件的行。但是,当连续出现错误时,它会停止循环。有没有办法告诉 python 跳过错误并移动到下一行?我使用了 try 函数但没有工作。我的代码是
感谢您提供的优秀示例,我试过了,它按我的预期工作。很高兴看到有人了解问题的本质。但是,我认为我应该用 Lift 标记问题,因为我正在使用 Lift 框架,这就是(仍然)发生这个问题的地方(尽管我仍然认
大家好,我正在编写一个算法来从 NodeTree 中删除具体分支(例如 DSF)。如果您选择 Node 的名称,算法将检查该 Node 是否是其他 Node 的父 Node ;如果是,它会获取该 No
附有代码和输出。 基本上它是第二次跳过我的输入。就像我启动代码一样,它让我输入一个选项,然后第二次跳过输入,直接转到开关的默认情况。 然后第三次它就会允许我输入。不明白为什么。 任何帮助将不胜感激。
我在 JavaScript 中有一个 for 循环,它会定期跳过间隔,但我无法确定原因。 console.log(parseInt($('input.num-to-add').val())); num
我正在 JasperSoft 中填写参数。在我的报告中我有参数:参数_1、参数_2、参数_3 int a; for (a = 0; a < headers.length; a++) {
我是一名优秀的程序员,十分优秀!