0
votes

I have plotted a stacked bar chart (see here: https://imgur.com/a/ESJeHuF), formed out of the dataframe below.

                            condition1       condition2      condition3
timestamp                                                
2019-10-30 01:41:43             1.0             4.0             0.0
2019-10-30 01:50:11             1.0             2.0             4.0
2019-10-30 01:50:59             1.0             2.0             4.0
2019-10-30 01:51:36             1.0             2.0             4.0
2019-10-30 01:52:27             1.0             3.0             4.0
2019-10-30 01:53:10             2.0             4.0             0.0
2019-10-31 02:25:14             5.0             0.0             0.0
2019-10-31 04:15:54             5.0             0.0             0.0

I would like the colors in the bar chart to match their corresponding values in the dataframe via this color list:

color_list = ['r', 'g', 'b', 'm', 'k', 'k']

(e.g. if a value for the 2nd to last timestep is 5, to color the segment of the stacked bar chart as 'k', with that behavior repeated for all segment of the stacked bar chart columns.

The code below plots the stacked bars, however miscolors them (the link above shows this). It only assigns the first three colors to all of the values, where there are more corresponding colors/values in the Dataframe. The correct plot should have the timestamps on the x-axis, and the segments of the bars for each condition the correct colors.

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
data_color = [0.,1.,2.,3.,4.,5.] #data range from conditions columns
data_color = [x / max(data_color) for x in data_color]   
print(data_color)
custom_map = plt.cm.get_cmap('Accent') #one of the color schemas stored
custom = custom_map(data_color)  #mapping the color info to the variable custom
print(custom)
fig = plt.figure()
ax = fig.add_subplot(111)
df.plot.bar(stacked=True, rot=1, legend=False, ax=fig.gca(), color=custom)

I would greatly appreciate any help, thank you in advance.

1

1 Answers

0
votes

IIUC you'd like to have all bars of same hight have the same color. I'm not sure if it can be done using color mappling but you can manually color the bars after creating the plot:

color_list = ['r', 'g', 'b', 'm', 'k', 'c']
plot = df.plot.bar(stacked=True, legend=False)
for bar in plot.patches:
    bar.set_color(color_list[int(bar.get_height())])

enter image description here