我想将函数下降到'-1‘的部分曲线图替换为从上一点开始的虚线(参见下面的曲线图)。
下面是我写的一些代码,以及它的输出:
import numpy as np
import matplotlib.pyplot as plt
y = [5,6,8,3,5,7,3,6,-1,3,8,5]
plt.plot(np.linspace(1,12,12),y,'r-o')
plt.show()
for i in range(1,len(y)):
if y[i]!=-1:
plt.plot(np.linspace(i-1,i,2),y[i-1:i+1],'r-o')
else:
y[i]=y[i-1]
plt.plot(np.linspace(i-1,i,2),y[i-1:i+1],'r--o')
plt.ylim(-1,9)
plt.show()这是原始的情节

修改后的图:

我写的代码可以工作(它会产生所需的输出),但是当我在我的(更大的)数据集上实际运行它时,它的效率很低,并且需要很长时间。有没有更聪明的方法来做这件事呢?
发布于 2018-01-15 18:18:32
我将使用numpy功能将您的线切成线段,然后分别绘制所有实线和虚线。在下面的示例中,我向您的数据中添加了两个额外的-1,以查看这是通用的。
import numpy as np
import matplotlib.pyplot as plt
Y = np.array([5,6,-1,-1, 8,3,5,7,3,6,-1,3,8,5])
X = np.arange(len(Y))
idxs = np.where(Y==-1)[0]
sub_y = np.split(Y,idxs)
sub_x = np.split(X,idxs)
fig, ax = plt.subplots()
##replacing -1 values and plotting dotted lines
for i in range(1,len(sub_y)):
val = sub_y[i-1][-1]
sub_y[i][0] = val
ax.plot([sub_x[i-1][-1], sub_x[i][0]], [val, val], 'r--')
##plotting rest
for x,y in zip(sub_x, sub_y):
ax.plot(x, y, 'r-o')
plt.show()结果如下所示:

但是,请注意,如果第一个值为-1,则此操作将失败,因为您的问题没有明确定义(没有以前的值可供复制)。希望这能有所帮助。
发布于 2018-01-16 02:51:39
您可以在不使用循环的情况下实现类似的结果:
import pandas as pd
import matplotlib.pyplot as plt
# Create a data frame from the list
a = pd.DataFrame([5,6,-1,-1, 8,3,5,7,3,6,-1,3,8,5])
# Prepare a boolean mask
mask = a > 0
# New data frame with missing values filled with the last element of
# the previous segment. Choose 'bfill' to use the first element of
# the next segment.
a_masked = a[mask].fillna(method = 'ffill')
# Prepare the plot
fig, ax = plt.subplots()
line, = ax.plot(a_masked, ls = '--', lw = 1)
ax.plot(a[mask], color=line.get_color(), lw=1.5, marker = 'o')
plt.show()

您还可以通过为线条选择不同的颜色来突出显示负片区域:

我的答案是基于2017年7月的一篇很棒的帖子。后者还处理第一个元素为NaN或在本例中为负数时的情况:Dotted lines instead of a missing value in matplotlib
发布于 2018-01-16 19:00:24
不太优雅,但这里有一些不使用循环的东西,这是我想出来的(基于上面的答案),可以工作。@KRKirov和@Thomas Kühn,感谢你们的回答,我真的很感谢他们
import pandas as pd
import matplotlib.pyplot as plt
# Create a data frame from the list
a = pd.DataFrame([5,6,-1,-1, 8,3,5,7,3,6,-1,3,8,5])
b=a.copy()
b[2]=b[0].shift(1,axis=0)
b[4]=(b[0]!=-1) & (b[2]==-1)
b[5]=b[4].shift(-1,axis=0)
b[0] = (b[5] | b[4])
c=b[0]
d=pd.DataFrame(c)
# Prepare a boolean mask
mask = a > 0
# New data frame with missing values filled with the last element of
# the previous segment. Choose 'bfill' to use the first element of
# the next segment.
a_masked = a[mask].fillna(method = 'ffill')
# Prepare the plot
fig, ax = plt.subplots()
line, = ax.plot(a_masked, 'b:o', lw = 1)
ax.plot(a[mask], color=line.get_color(), lw=1.5, marker = 'o')
ax.plot(a_masked[d], color=line.get_color(), lw=1.5, marker = 'o')
plt.show()https://stackoverflow.com/questions/48260014
复制相似问题