Matplotlib散点图在图例和图中绘制不同的颜色 [英] Matplotlib scatter plot different colors in legend and plot
问题描述
在matplotlib(python 2.7)中,我对同一个x值有多个y值的散点图.所有绘制的y值都有不同的颜色.参见下面的图.
现在,这是代码:
将numpy导入为np将熊猫作为pd导入导入matplotlib.pyplot作为plt导入pylab为pl将cmplotlib.cm导入为cm#生成测试x,y和y_error值:df2a = pd.DataFrame(np.random.rand(10,5),列= 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),列= df2a.columns.tolist()[1:])df2a_err.insert(0,'x_var_plot',range(1,df2a.shape [0] +1))无花果= plt.figure(1)斧= fig.add_subplot(111)![错误栏问题] [1]颜色= iter(cm.rainbow(np.linspace(0,1,df2a.shape [1])))#生成图:对于df2a.columns.values.tolist()[1:]中的col: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',分散点= 1)plt.show()
问题在于,图解符号中的颜色与图例中的符号颜色完全不同.当我添加错误栏时,会出现问题.图例符号颜色与散点图误差线之间的连接有问题.
当包含误差线时,是否有办法解决此问题,使图例中的颜色与散点图的颜色相同?
在图中,误差线和散布图点有不同的颜色.您可以像这样使它们相同:
<上一个> <代码> c =下一个(颜色)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)
I have a scatter plot of multiple y-values for the same x-value, in matplotlib (python 2.7). There are different colors for all the plotted y-values. See the plot below.
Now, here is the code:
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()
The problem is that the colors in the plot symbols are completely different from the symbol colors in the legend. The problem occurs when I add errorbars. Something is wrong between the connection between the legend symbol color and the scatter plot error bars.
Is there is a way to fix this so that the colors in the legend are the same as the colors of the scatter plot points, when I include error bars?
In your plot there are different colors for the error bars and the scatter plot points. You can make them the same like this:
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)
这篇关于Matplotlib散点图在图例和图中绘制不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!