尝试在Python中绘制多色线时出错

时间:2016-11-19 15:57:56

标签: python matplotlib plot

我无法通过引用索引来绘制点着色的变量。我最终想要的是每个点(连接到下一个点)的线段是特定的颜色。我尝试了Matplotlibpandas。每种方法都会抛出不同的错误。

生成趋势线:

datums = np.linspace(0,10,5)
sinned = np.sin(datums)

plt.plot(sinned)

edgy sin graph

现在我们生成一个新的标签列:

sinned['labels'] = np.where((sinned < 0), 1, 2)
print(sinned)

生成我们的最终数据集:

          0  labels
0  0.000000       2
1  0.598472       2
2 -0.958924       1
3  0.938000       2
4 -0.544021       1

现在为了密谋尝试:

plt.plot(sinned[0], c = sinned['labels'])

导致错误:length of rgba sequence should be either 3 or 4

我还尝试将标签设置为字符串'r''b',这些字符串不起作用:-/

1 个答案:

答案 0 :(得分:1)

1和2不是颜色,'b' lue和'r' ed在下面的示例中使用。你需要分别绘制每个。

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

datums = np.linspace(0,10,5)

sinned = pd.DataFrame(data=np.sin(datums))
sinned['labels'] = np.where((sinned < 0), 'b', 'r')
fig, ax = plt.subplots()

for s in range(0, len(sinned[0]) - 1):
    x=(sinned.index[s], sinned.index[s + 1])
    y=(sinned[0][s], sinned[0][s + 1])
    ax.plot(x, y, c=sinned['labels'][s])
plt.show()

Output

相关问题