I'm quite new in python and been working with pandas & matplotlib a lot recently to display data at work. I am trying to plot a vibration chart, where x-axis is the depth (in meter) and y-axis is the vibration level (Axial Z max.).I want to display the vibration level in 4 different colors:
- Green is for low level (values <= 1.5)
- Orange for medium (values 1.5 < 2.5)
- Red for high (values 2.5 < 5)
- Maroon for severe (values >= 5).
I have read documentation for matplotlib multicolored line and managed to produce a plot that i want to create. However i still don't understand why it works, there are some lines where i didn't understand the code and how it works in my plot that is why im posting this question to get some clarity. My questions:
- What are the points and segments for? Why do i have to reshape and concatenate them?
- what does lc.set_array(y) do in this code?
- Is there any way i can make the code shorter and more tidy especially the part where i assign label, line width and autoview? Can I combine all of them in one line? Instead of writing each line for each attribute.
Thank you so much for your help !
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
df = pd.read_excel("C:/Users/AmeliaB/Documents/Python/8-5in_plotting.xlsx", header=0)
df['DATETIME'] = pd.to_datetime(df.DATETIME)
# define variables
y = np.array(df["DHT001_Accel_Axial_Z_Max"])
x = np.array(df["Hole_Depth"])
# Create a set of line segments so we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be (numlines) x (points per line) x 2 (for x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
fig, ax = plt.subplots(1)
cmap = ListedColormap(['green', 'orange', 'red', "maroon"])
norm = BoundaryNorm([1, 1.5, 2.5, 5, 5.5], cmap.N)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(y)
lc.set_linewidth(1) # The thickness of the line
ax.add_collection(lc)
ax.autoscale_view()
fig.colorbar(lc) #Add colorbar
plt.xlabel ("Hole depth")
plt.ylabel ("Vibration level")
plt.show()
