Matplotlib scatter plot different colors in legend and plot

ε祈祈猫儿з 提交于 2020-01-30 02:48:29

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/27326881/matplotlib-scatter-plot-different-colors-in-legend-and-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!