问题:
我有两列数据(public static long getThreadId(Context context, String phoneNumber) {
Uri threadIdUri = Uri.parse("content://mms-sms/threadID");
Uri.Builder uriBuilder = threadIdUri.buildUpon();
uriBuilder.appendQueryParameter("recipient", phoneNumber);
Uri uri = uriBuilder.build();
Cursor cursor = context.getContentResolver().query(uri,
new String[]{"_id"} /* projection */,
null /* selection */,
null /* selectionArgs */,
null /* order */);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(0);
}
} finally {
cursor.close();
}
}
return 0;
}
和x
点),第三列有标签(值y
或0
)。我想在散点图上绘制1
和x
,并根据标签是y
还是0
对其进行着色,我想要一个右边的颜色条剧情。
以下是我的数据:https://www.dropbox.com/s/ffta3wgrl2vvcpw/data.csv?dl=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
参数的文档对我来说是不可理解的。究竟是什么?
文档:http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.colorbar
答案 0 :(得分:1)
你需要传递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)
对于ticks
,您要在颜色栏上传递一个列表。因此,在您的示例中,您的刻度为0,刻度为1。
我还修复了你的cmap,从红色变为绿色。你需要告诉散点图也使用cmap。