Matplotlib散点图和图中的不同颜色
问题描述:
我在matplotlib(python 2.7)中有一个相同x值的多个y值的散点图。所有绘制的y值有不同的颜色。看下面的情节。Matplotlib散点图和图中的不同颜色
现在,这里是代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pylab as pl
import matplotlib.cm as cm
# Generate test x, y and y_error values:
df2a = pd.DataFrame(np.random.rand(10,5), columns = list('ABCDE'))
df2a.insert(0,'x_var_plot',range(1,df2a.shape[0]+1))
df2a_err = pd.DataFrame(np.random.rand(df2a.shape[0],df2a.shape[1]-1), columns = df2a.columns.tolist()[1:])
df2a_err.insert(0,'x_var_plot',range(1,df2a.shape[0]+1))
fig = plt.figure(1)
ax = fig.add_subplot(111)
![Errorbars problem][1]
colors = iter(cm.rainbow(np.linspace(0, 1, df2a.shape[1])))
# Generate plot:
for col in df2a.columns.values.tolist()[1:]:
ax.errorbar(df2a['x_var_plot'], df2a[col], yerr=df2a_err[col], fmt='o')
ax.scatter(df2a['x_var_plot'], df2a[col], color=next(colors), label=col)
ax.legend(loc='best', scatterpoints = 1)
plt.show()
的问题是,在绘图符号的颜色是从图例中的符号颜色完全不同。当我添加错误栏时会发生问题。图例符号颜色和散点图错误栏之间的连接有些不对劲。
有没有办法解决这个问题,使图例中的颜色与散点图的颜色相同,当我包含错误条?
答
在您的图中,误差线和散点图有不同的颜色。你可以让他们像这样一样:
c = next(colors)
ax.errorbar(df2a['x_var_plot'], df2a[col], color = c, yerr=df2a_err[col], fmt='o')
ax.scatter(df2a['x_var_plot'], df2a[col], color = c, label=col)
嘿,谢谢。它工作正常。 – 2014-12-06 05:34:33