I do have the following data:
- x_values (which are monotonic ascending from about -300 to 100)
- y1_values (which are random from 0 to 150)
- y2_values (which are random from -1 to 1)
- colorInfo (which can be 0, 1, 2 (for blue, red, green))
So: Now I want to plot y1 and y2 over x, where the plot is colored in the color given by colorInfo
My data (which I get from a csv file) could look like this:
x | y1 | y2 | color
-300 | 50 | 0.5 | 0
-298 | 51 | 0.4 | 0
-295 | 51 | 0.2 | 1
-292 | 44 | 0.1 | 1
So I want the plot of y1 and y2 to be colored like:
from -300 to -298: blue
from -298 to -295: blue
from -295 to -292: red
Now I have the following code (which is basically a modified version of: https://matplotlib.org/1.5.0/examples/pylab_examples/multicolored_line.html):
import csv, os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
import tkinter as tk
from tkinter import filedialog
def plotter(filepath):
data = read_csv(os.path.abspath(filepath))
x_values = [None if data["x"] is '' else float(data["x"]) for data["x"] in data["x"]]
y1_values = [None if data["y1"] is '' else float(data["y1"]) for data["y1"] in data["y1"]]
y2_values = [None if data["y2"] is '' else float(data["y2"]) for data["y2"] in data["y2"]]
colorInfo = [None if data["color"] is '' else float(data["color"]) for data["color"] in data["color"]]
cmap = ListedColormap(['b', 'r', 'g'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
points = np.array([x_values, y1_values]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, norm=plt.Normalize(0, 10))
lc.set_array(colorInfo)
lc.set_linewidth(3)
fig1 = plt.figure()
plt.gca().add_collection(lc)
plt.show()
def read_csv(filename):
data = {}
with open(filename) as csvfile:
csvreader = csv.DictReader(csvfile, delimiter=',')
for row in csvreader:
for key in row.keys():
if key not in data:
data[key] = []
data[key].append(row[key])
return data
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
plotter(file_path)
the minimal csv file is:
x,y1,y2,color
-300,40,1,0
-298,42,1,0
-291.2,44,1,0
-261,48,0.6,1
-245,51,0.5,1
-236,54,0.5,1
-221,48,0.3,1
-210,40,0.1,1
-150,38,-0.2,1
-130,37,-1,1
-110,35,-1,1
-50,30,0.5,2
-10,25,0.5,2
0,20,0.6,2
5,21,1,2
50,30,0.6,0
70,40,0.2,0
80,50,1,0
100,60,1,0
This only shows a white screen. I guess I need the lc.set_array. But I do have the problem that I can only set this to a function and not to my defined points.
Any suggestions?

set_arraydoes not accept functions. It only accepts arrays or lists. Since you have your color information in a list, this should be directly applicable. If you have a problem with that you need to provide a runnable example (see minimal reproducible example) such that one can test at which point the problem occurs.open()on a file.