matplotlib散点图的颜色参数是`c`,但`color`也可用;效果差异大
我不小心在matplotlib的散点图中用color
代替了c
作为颜色参数(c
在文档中有说明)。结果是可以运行,但显示的效果不一样:默认情况下边缘颜色消失了。现在我在想,这样的结果是否是预期的,以及这是怎么回事,为什么会这样……
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10,10))
samples = np.random.randn(30,2)
ax[0][0].scatter(samples[:,0], samples[:,1],
color='red',
label='color="red"')
ax[1][0].scatter(samples[:,0], samples[:,1],
c='red',
label='c="red"')
ax[0][1].scatter(samples[:,0], samples[:,1],
edgecolor='white',
c='red',
label='c="red", edgecolor="white"')
ax[1][1].scatter(samples[:,0], samples[:,1],
edgecolor='0',
c='1',
label='color="1.0", edgecolor="0"')
for row in ax:
for col in row:
col.legend(loc='upper left')
plt.show()
1 个回答
6
这不是一个错误,而是我觉得matplotlib
文档有点模糊。
标记的颜色可以通过c
、color
、edgecolor
和facecolor
来定义。
c
是在scatter()
这个函数的源代码中定义的,它在axes.py
文件里。c
相当于facecolor
。当你使用c='r'
时,edgecolor
没有被定义,这时就会使用matplotlib.rcParams
中的默认值,而这个默认值是k
(黑色)。
color
、edgecolor
和facecolor
会传递给scatter()
返回的collection.Collection
对象。你会在源代码collections.py
中看到(set_color()
、set_edgecolor()
和set_facecolor()
方法),set_color()
基本上是调用set_edgecolor
和set_facecolor
,因此这两个属性会被设置成相同的值。
这些我希望能解释你在原帖中描述的行为。在c='red'
的情况下,边缘是黑色,面色是红色。而在color=red
的情况下,面色和边缘颜色都是红色。