Python 有关如何使用matplotlib.colorbar的详细信息
问题: 我有两列数据(Python 有关如何使用matplotlib.colorbar的详细信息,python,matplotlib,colorbar,Python,Matplotlib,Colorbar,问题: 我有两列数据(x和y点),第三列有标签(值0或1)。我想在散点图上绘制x和y,并根据标签是0还是1来给它们上色,我想在绘图的右侧有一个色条 以下是我的数据: 注:我知道,因为只有两个标签,我只会得到两种颜色,尽管使用了色条;但是这个数据集只是作为一个例子 我到目前为止所做的事情 import matplotlib.pyplot as plt import csv import matplotlib as m #read in the data with open('data.csv',
x
和y
点),第三列有标签(值0
或1
)。我想在散点图上绘制x
和y
,并根据标签是0
还是1
来给它们上色,我想在绘图的右侧有一个色条
以下是我的数据:
注:我知道,因为只有两个标签,我只会得到两种颜色,尽管使用了色条;但是这个数据集只是作为一个例子
我到目前为止所做的事情
import matplotlib.pyplot as plt
import csv
import matplotlib as m
#read in the data
with open('data.csv', 'rb') as infile:
data=[]
r = csv.reader(infile)
for row in r:
data.append(row)
col1, col2, col3 = [el for el in zip(*data)]
#I'd like to have a colormap going from red to green:
cdict = {
'red' : ( (0.0, 0.25, 0), (0.5, 1, 1), (1., 0.0, 1.)),
'green': ( (0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1., 1.0, 1.0)),
'blue' : ( (0.0, 0.0, 0.0), (1, 0.0, 0.0), (1., 0.0, 0.0))}
cm = m.colors.LinearSegmentedColormap('my_colormap', cdict)
# I got the following line from an example I saw; it works for me,
# but I don't really know how it works as an input to colorbar,
# and would like to know.
formatter = plt.FuncFormatter(lambda i, *args: ['0', '1'][int(i)])
plt.figure()
plt.scatter(col1, col2, c=col3)
plt.colorbar(ticks=[0, 1], format=formatter, cmap=cm)
由于调用了plt.colorbar
,上述代码无法工作
ticks
参数的文档对我来说是不可理解的。到底是什么
文件:您需要传递
col3
以分散为浮点数组,而不是元组和整数
因此,这应该是可行的:
import matplotlib.pyplot as plt
import csv
import matplotlib as m
import numpy as np
#read in the data
with open('data.csv', 'rb') as infile:
data=[]
r = csv.reader(infile)
for row in r:
data.append(row)
col1, col2, col3 = [el for el in zip(*data)]
#I'd like to have a colormap going from red to green:
cdict = {
'red' : ( (0.0, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)),
'green': ( (0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)),
'blue' : ( (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0))}
cm = m.colors.LinearSegmentedColormap('my_colormap', cdict)
#I got the following line from an example I saw; it works for me, but I don't really know how it works as an input to colorbar, and would like to know.
formatter = plt.FuncFormatter(lambda i, *args: ['0', '1'][int(i)])
plt.figure()
plt.scatter(col1, col2, c=np.asarray(col3,dtype=np.float32),lw=0,cmap=cm)
plt.colorbar(ticks=[0, 1], format=formatter, cmap=cm)
对于记号
,您将在颜色栏上传递一个想要记号的位置列表。因此,在您的示例中,0处有一个记号,1处有一个记号
我还修复了您的cmap,从红色变为绿色。您需要告诉scatter也使用cmap