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.

fig = plt.figure()
ax = fig.add_subplot(111)
df.plot.bar(stacked=True, rot=1, legend=False, ax=fig.gca(), colors=color_list)

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

1

1 Answers

0
votes

I don't know how important to you is the choice of colors. I've just found a solution that seems to fix your problem, the only "but" is that is the development is easier if you accept one of the color schema's available. Othewrise, if you will have to make a colormap by hand, you can find examples with LinearSegmentedColormap from matplotlib.colors.

The code:

    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]   

    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

    fig = plt.figure()
    ax = fig.add_subplot(111)
    df.plot.bar(stacked=True, rot=1, legend=False, ax=fig.gca(), color=custom)

    plt.show()

The display:

enter image description here