Matplotlib散点图在图例和图中使用不同的颜色

时间:2014-12-06 00:32:40

标签: python-2.7 matplotlib legend legend-properties colormap

我在matplotlib(python 2.7)中有相同x值的多个y值的散点图。所有绘制的y值都有不同的颜色。见下图。

Errorbars of wrong symbol color than legend

现在,这是代码:

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()

问题是绘图符号中的颜色与图例中的符号颜色完全不同。添加错误栏时会出现此问题。图例符号颜色与散点图错误条之间的连接有问题。

当我包含错误栏时,有没有办法解决这个问题,以便图例中的颜色与散点图颜色的颜色相同?

1 个答案:

答案 0 :(得分:2)

在绘图中,误差条和散点图有不同的颜色。你可以这样做:

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)

enter image description here