Home > OS >  Is there a simple way to plot related traces with similar colors in matplotlib?
Is there a simple way to plot related traces with similar colors in matplotlib?

Time:01-13

I have multiple measurements from three different sensors. I want to plot all measurements from sensor A in a bluish color, from sensor B in a yellowish and from sensor C in a redish color.

Is there a simple way to achive this with matplotlib, i.e. different colormaps or something?

I plotted related measurements in the same color, but then I can't distinguish the different measurements. I could create my own colormaps, but that seems tedious.

My data looks something like this:

Measurement 1:

Time Sensor A Sensor B Sensor C
0 h 20°C 18°C 16°C
1 h 21°C 19°C 16°C
2 h 20°C 19°C 17°C

Measurement 2:

Time Sensor A Sensor B Sensor C
0 h 19°C 19°C 15°C
1 h 21°C 18°C 16°C
2 h 20°C 19°C 14°C

Measurement 3:

Time Sensor A Sensor B Sensor C
0 h 21°C 18°C 16°C
1 h 22°C 19°C 16°C
2 h 20°C 19°C 17°C

enter image description here

CodePudding user response:

Edit

I think it would be easier to use different linestyles or markers for different measurements. It depends on whether it is more important to compare different sensors in one measurement or the same sensor data in different measurements.

Old answer

You should be able to simply supply colors so you get lines in three different colors by calling the plot function three times with the color argument:

from matploltib import pyplot as plt

plt.plot(x_A, y_A, color='r')
plt.plot(x_B, y_B, color='g')
plt.plot(x_C, y_C, color='b')

CodePudding user response:

Based on the link in my comment, you can loop over the sensor-measurement combinations to create a colormap based on Matplotlib's existing RdYlBu.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pylab as pyl
import numpy as np
from itertools import product

measurement_list = [df1, df2, df3] # The 3 measurement dataframes from your example
sensor_list = sorted(df1.filter(like='Sensor').columns)

# n is the number of sensors x the number of measurements
n = len(measurement_list) * len(sensor_list)

# Use the reverse order of RdYlBu to get the color combination you specified
colors = pyl.cm.RdYlBu_r([0.1,0.15,0.2,0.5,0.5,0.55,0.6, 0.85,0.9,0.95]) # play around with to get the boundaries and number you need
# Be less specific with color boundaries and just get the number you want
#colors = pyl.cm.RdYlBu_r(np.linspace(0,1,n)) 

fig, ax = plt.subplots(figsize=(8,6))

# Get the combinations without replacement of the sensor-measurement pairs
ms_combos = product(sensor_list, measurement_list)

for idx, (sensor, df) in enumerate(ms_combos):
    # Plot each sensor's readings and label by sensor and measurement
    ax.plot(df['Time'], df[sensor], color = colors[idx], label = f'{sensor} - Meas. {idx%3 1}')
    
ax.set(xlabel = 'Time [h]', ylabel = 'Temperature [C]')
ax.legend()

plt.show()

enter image description here

  • Related