Reputation: 23
I am new at Matplotlib and would like to assign colors to error bar caps...in my data (attached) the mean values are 'numbers' and the SD ('error') is in the column 'sd'. I grouped data by 'strain' (4 categories; mc, mut1, etc.). Colors are 'strains' (lines). The code below works BUT When I use "capsize" to add caps it throws an error...
I want the caps to have the same color as lines (from color vector "c"), any way? Thanks!
The file is https://anonfiles.com/d8A7m4F5o0/mutdp_csv
muts = pd.read_csv('mutdp.csv')
#SUBSET
# Select rows (i.e. 1 to 28)
gr=muts[1:28]
fig, ax = plt.subplots(figsize=(12,9.9))
c=['b','y','r','g']
#Data GR ---------------------------------------------------------------------------------------------
grstrain=gr.groupby(['time','strain']).mean()['numbers'].unstack()
grstrain.plot.line(ax=ax, style=['-o','-o','-o','-o'],color=c, ls = '--', linewidth=2.7)
# Error (-----HERE is where "capsize" causes the error----)
ax.errorbar(gr.time, gr.numbers, yerr=gr.sd, ls='', color=[i for i in c for _i in range(7)], capsize=3, capthick=3)
#(SCALE)
plt.yscale('log')
plt.ylim(0.04, 3)
#SAVE FIG!
plt.show()
Upvotes: 0
Views: 1305
Reputation: 80319
As ax.errorbar
only accepts one fixed color, it could be called in a loop, once for each color. The following code creates some random data to show how the loop could be written:
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
gr = pd.DataFrame({'time': np.tile(range(0, 14, 2), 4),
'strain': np.repeat(['mc', 'mut1', 'mut2', 'mut3'], 7),
'numbers': 0.1 + np.random.uniform(-0.01, 0.06, 28).cumsum(),
'sd': np.random.uniform(0.01, 0.05, 28)})
fig, ax = plt.subplots(figsize=(12, 9.9))
colors = ['b', 'y', 'r', 'g']
grstrain = gr.groupby(['time', 'strain']).mean()['numbers'].unstack()
grstrain.plot.line(ax=ax, style=['-o', '-o', '-o', '-o'], color=colors, ls='--', linewidth=2.7)
for strain, color in zip(np.unique(gr.strain), colors):
grs = gr[gr.strain == strain]
ax.errorbar(grs.time, grs.numbers, yerr=grs.sd, ls='', color=color, capsize=3, capthick=3)
plt.yscale('log')
plt.ylim(0.04, 3)
plt.show()
Upvotes: 1