更改matplotlib线型中图

时间:2012-02-14 22:04:32

标签: python styles matplotlib line graphing

我正在绘制一些数据(两行),我想更改线条部分的线条样式,它们之间的差异具有统计显着性。所以,在下图中(现在链接b / c反垃圾邮件策略不允许我发布图像)我希望线条看起来不同(也许是虚线),直到它们开始收敛于35左右x轴。

line plot

有没有办法轻松完成这项工作?我有x轴的值,差异很大,我不清楚如何在某些x轴位置更改线条样式。

2 个答案:

答案 0 :(得分:15)

编辑:我已经打开并离开,所以我没有注意到@里卡多的回答。因为matplotlib会将事物转换为numpy数组,所以有更有效的方法来实现它。

举个例子:

只需绘制两条不同的线条,一条是虚线样式,另一条是实线样式。

E.g。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y1 = 2 * x
y2 = 3 * x

xthresh = 4.5
diff = np.abs(y1 - y2)
below = diff < xthresh
above = diff >= xthresh

# Plot lines below threshold as dotted...
plt.plot(x[below], y1[below], 'b--')
plt.plot(x[below], y2[below], 'g--')

# Plot lines above threshold as solid...
plt.plot(x[above], y1[above], 'b-')
plt.plot(x[above], y2[above], 'g-')

plt.show()

enter image description here

对于它们是循环的情况,使用蒙版数组:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y1 = 2 * np.cos(x)
y2 = 3 * np.sin(x)

xthresh = 2.0
diff = np.abs(y1 - y2)
below = diff < xthresh
above = diff >= xthresh

# Plot lines below threshold as dotted...
plt.plot(np.ma.masked_where(below, x), np.ma.masked_where(below, y1), 'b--')
plt.plot(np.ma.masked_where(below, x), np.ma.masked_where(below, y2), 'g--')

# Plot lines above threshold as solid...
plt.plot(np.ma.masked_where(above, x), np.ma.masked_where(above, y1), 'b-')
plt.plot(np.ma.masked_where(above, x), np.ma.masked_where(above, y2), 'g-')

plt.show()

enter image description here

答案 1 :(得分:3)

假设您的数据位于NumPy数组dataset1dataset2上,并且您已将threshold定义为您的重要性

def group(data):
    """Assumes that len(data) > 0"""
    prev = 0
    index = 1
    value = data[0]

    while (index < len(data)):
        if data[index] != value:
            yield (value, prev, index)

            value = not value
            prev = index
        index += 1

    yield (value, prev, index)

diff = np.abs(dataset1 - dataset2)
for significant, start, end in group(diff < threshold):
   # Plot data from dataset1[start:end] and dataset2[start:end]
   # Use the value in "significant" (True/False) to figure out
   # The style