简体   繁体   English

如何为误差线上限分配颜色? [Matplotlib]

[英]How to assign color to error bar caps? [Matplotlib]

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'.我是 Matplotlib 的新手,想将 colors 分配给误差线上限……在我的数据(附加)中,平均值是“数字”,SD(“错误”)在“sd”列中。 I grouped data by 'strain' (4 categories; mc, mut1, etc.).我按“应变”(4 个类别;mc、mut1 等)对数据进行分组。 Colors are 'strains' (lines). Colors 是“菌株”(线)。 The code below works BUT When I use "capsize" to add caps it throws an error...下面的代码有效,但是当我使用“capsize”添加大写时,它会引发错误......

I want the caps to have the same color as lines (from color vector "c"), any way?我希望帽子与线条具有相同的颜色(来自颜色矢量“c”),无论如何? Thanks!谢谢!

The file is https://anonfiles.com/d8A7m4F5o0/mutdp_csv该文件是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() 

As ax.errorbar only accepts one fixed color, it could be called in a loop, once for each color.由于ax.errorbar只接受一种固定颜色,因此可以循环调用它,每种颜色一次。 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()

示例图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM