2

I have a code which assigns a legend to each element of the datalist (17 different colors), including the same color of the errorbars.

In the process I have found very useful answers for the coloring of the plots within a loop (like in the post: Setting different color for each series in scatter plot on matplotlib) , for which I get an image like this:

enter image description here

The question is: how to offset each series for a dx for every iSub when having a timeseries as x axis so that the scatter plots of each iSub don't overlap?

from datetime import datetime, timedelta
import matplotlib.cm as cm
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np


def datetime_range(start, end, delta):
    current = start
    while current < end:
        yield current
        current += delta


nSub = 17
nTimes = 34

datalist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']


DATA = np.random.uniform(low=0.5, high=50.0, size=(nSub,nTimes))

DZ = np.random.rand(nSub,nTimes)

timelist = [dt.strftime('%Y-%m-%d') for dt in 
   datetime_range(datetime(2012, 1, 1), datetime(2014, 8, 1), 
   timedelta(weeks=4))]
datelist = [datetime.strptime(timelist[i], '%Y-%m-%d') for i in range(len(timelist))]

fig, ax = plt.subplots (nrows=1, ncols=1)

colors = cm.rainbow(np.linspace(0, 1, len(datalist)))

for isub in range(len(datalist)):

    ax.scatter(datelist, DATA[isub], label=datalist[isub], color = colors[isub]) 
    ax.errorbar(datelist, DATA[isub], yerr = DZ[isub], color = colors[isub], fmt='o', markersize=8, capsize=20)

    ax.set_xlim([datetime(2011,12,1).toordinal(), datetime(2015,1,1).toordinal()] )

    ax.xaxis.set_tick_params(labelsize=20)
    ax.yaxis.set_tick_params(labelsize=20)

    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

fig.set_size_inches(40,20)
PEBKAC
  • 748
  • 1
  • 9
  • 28
  • 1
    You can specify the color of the error bars using the keyword `ecolor` in your `ax.errorbar()` method. See here: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.errorbar.html – rahlf23 Jul 20 '18 at 14:09
  • yes, I saw this but how do you specify it so it matches the colors of the scatterplots? what should the `ecolor` be set equal to? – PEBKAC Jul 20 '18 at 14:12
  • 1
    The default behavior according to the docs is that the error bar colors will match the associated scatter data color. – rahlf23 Jul 20 '18 at 14:14
  • however it didn't prove to work for a more complex dataset. See changes in the code above. – PEBKAC Jul 20 '18 at 17:33
  • There is a comma missing between the `color` and `fmt` argument in `color = colors[isub] fmt='o'`. – ImportanceOfBeingErnest Jul 20 '18 at 21:39
  • Thank you very much, I corrected it @ImportanceOfBeingErnest – PEBKAC Jul 21 '18 at 07:20

0 Answers0