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

2024-05-15 14:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法绘制一个变量,其中点是通过引用索引着色的。我最终想要的是每个点(连接到下一个点)的线段是一种特定的颜色。我尝试了Matplotlib和{}。每个方法抛出不同的错误。在

生成趋势线:

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

plt.plot(sinned)

edgy sin graph

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

^{pr2}$

生成最终数据集:

          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'或{},但这两个字符串:-/都不起作用


Tags: 方法字符串labelsplotmatplotlib颜色错误np
1条回答
网友
1楼 · 发布于 2024-05-15 14:19:34

1和2不是颜色,'b'lue和{}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

相关问题 更多 >