Matplotlib 颜色图,散点图传递第三个颜色变量:RGBA 参数无效 [英] Matplotlib colormap, scatter plot passing a third variable for color: invalid RGBA argument

查看:49
本文介绍了Matplotlib 颜色图,散点图传递第三个颜色变量:RGBA 参数无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在matplotlib上构建报告.每个页面都有多个图表和一些文本.

报告数据中有 100 多个位置,每个位置都有一个密度.想法是在地图上绘制点,其中颜色(红色阴影)代表位置的密度.

但是,我不明白 ax.scatter 调用中 kwargs : c 和 cmap 之间的联系,也不了解 color.Normalize 在这个应用程序中的作用.

将pandas导入为pd导入 matplotlib将numpy导入为np从pandas import Series,DataFrame导入csv来自 scipy 导入统计导入matplotlib.pyplot作为plt随机导入导入 matplotlib.colors 作为颜色# 获取数据并转换数据= pd.read_csv('logHistThis.csv')data.drop('Unnamed:0',axis = 1,inplace = True)dataMean = data['密度'].mean()数据 = 列表(数据['密度'])#我很想知道色彩图的数据# 必须在 1 和 0 之间,所以这样做:aColorScale = []def myColorScale(theData):aColorScale = []对于theData中的x:这个= x/100aColorScale.append(this)返回一个ColorScaleaColorScale = myColorScale(数据)估计_mu,估计_sigma = stats.norm.fit(data)xmin = min(数据)xmax = 最大值(数据)x = np.linspace(xmin,xmax,100)pdf = stats.norm.pdf(x,loc = estimated_mu,scale = estimated_sigma)thisRangeMin = np.log(27)thisRangeMax = np.log(35)q = [np.random.choice(data, 40)]z = [ np.random.randint(1, 50, size=40)]s = 100 * q颜色图 = '红色'normalize =matplotlib.colors.Normalize(vmin=xmin, vmax=xmax)#plt.scatter(x,y,z,s=5, cmap=colormap, norm=normalize, marker='*')fig = plt.figure(figsize=(10, 5), frameon=False, edgecolor='000000', linewidth = 1)rect0 = .05, .05, .4, .9rect1 = .5, .05, .4, .9# 这个很好用ax1 = fig.add_axes(rect0)#< ----------- x2TopTenSummaryax1.hist(data, bins=13, normed=True, color='c', alpha=0.05)#ax1.fill_between(x,pdf,where =(),alpha = .2)ax1.fill_between(x,pdf,where =(((x< thisRangeMax)&(x> thisRangeMin)),alpha = .2,label ='City Range')ax1.vlines(dataMean, 0, stats.norm.pdf(dataMean, loc=estimated_mu, scale=estimated_sigma), color='r')ax1.plot(x, pdf, 'k')# 这不起作用:# 它只给出蓝点ax2 = fig.add_axes(rect1)ax2= fig.add_axes(rect1)ax2.scatter(q,z,s = 200,cmap ='Reds',norm = matplotlib.colors.Normalize(vmin = min(aColorScale),vmax = max(aColorScale))))#尝试通过多种方式设置颜色图:# 当 kwarg 'c' 设置为变量 'aColorScale' 我得到错误plt.show()plt.close()

所以我的问题是我们如何在这种应用程序中合并颜色图?

图形上具有预定大小(A4或字母)的多轴.颜色决定是第三个变量 z,(不是 x 或 y)颜色决定因素是一个浮点数,其中0 <0.&8电话是斧头不是 plt

我不清楚文档中应用程序的描述:

we are building our reports on matplotlib. Each page has multiple charts and some text.

In the report data there is over 100 locations, each location has a density. The idea is to plot the points on a map where the color (shade of red) represents the density of the location.

However, I do not understand the connection between the kwargs : c and cmap in the ax.scatter call, nor do I understand the role of color.Normalize in this application.

import pandas as pd
import matplotlib
import numpy as np
from pandas import Series, DataFrame
import csv
from scipy import stats
import matplotlib.pyplot as plt
import random
import matplotlib.colors as colors

# Get the data and transform
data = pd.read_csv('logHistThis.csv')
data.drop('Unnamed: 0', axis=1, inplace=True)
dataMean = data['Density'].mean()
data = list(data['Density'])

# I was under the impresion that the data for the colormap
# had to be between 1 and 0 so did this:
aColorScale = []
def myColorScale(theData):
    aColorScale = []
    for x in theData:
        this = x/100
        aColorScale.append(this)
    return aColorScale

aColorScale = myColorScale(data)

estimated_mu, estimated_sigma = stats.norm.fit(data)
xmin = min(data)
xmax = max(data)
x = np.linspace(xmin, xmax, 100)
pdf = stats.norm.pdf(x, loc=estimated_mu, scale=estimated_sigma)

thisRangeMin = np.log(27)
thisRangeMax = np.log(35)

q = [np.random.choice(data, 40)]
z = [ np.random.randint(1, 50, size=40)]
s = 100 *q


colormap = 'Reds'
normalize =matplotlib.colors.Normalize(vmin=xmin, vmax=xmax)
#plt.scatter(x,y,z,s=5, cmap=colormap, norm=normalize, marker='*')


fig = plt.figure(figsize=(10, 5), frameon=False, edgecolor='000000', linewidth = 1)

rect0 = .05, .05, .4, .9
rect1 = .5, .05, .4, .9

# This works great 
ax1 = fig.add_axes(rect0)#<-----------x2TopTenSummary
ax1.hist(data, bins=13, normed=True, color='c', alpha=0.05)
#ax1.fill_between(x, pdf, where=(), alpha=.2)
ax1.fill_between(x, pdf, where=((x <  thisRangeMax) & ( x > thisRangeMin)), alpha=.2, label='City Range')
ax1.vlines(dataMean, 0,  stats.norm.pdf(dataMean, loc=estimated_mu, scale=estimated_sigma), color='r')
ax1.plot(x, pdf, 'k')

# This does not work :
# It just gives blue dots
ax2= fig.add_axes(rect1)
ax2= fig.add_axes(rect1)
ax2.scatter(q,z, s=200,  cmap= 'Reds',norm=matplotlib.colors.Normalize(vmin=min(aColorScale) , vmax=max(aColorScale)))

# Tried to set the color map in a variety of ways:
# When kwarg 'c' is set to the variable 'aColorScale' i get the error

plt.show()
plt.close()

So my question is how do we incorporate the colormap in an application of this sort?

Multiple axes on a figure with a predetermined size (A4 or letter). The color determination is a third variable z, (not x or y) The color determinant is a float where 0 < z < 8 the call is ax not plt

The description of the application in the docs is unclear to me:

the doc for axes.scatter the doc for color.normalize

I have seen plenty of examples where there is only one ax in the figure and the call is to plt.scatter... for example here

In our case x, y will be longitude, lattitude and the variable is 'data' a list or array of floats between 0 and 8.

Thanks

解决方案

Okay the answer came from the PyCon Israel 2017 in this document by Tamir Lousky.

The normalization of the data and the correlation with color map happens with this block of code right here:

aColorScale = data
aColorScale = np.array(aColorScale)
norm = (aColorScale - aColorScale.min())/(aColorScale.max() - aColorScale.min())
cmap= plt.get_cmap('Reds')
colors = [cmap(tl) for tl in norm]#<---- thisRightHere

Then colors gets fed into ax2:

ax2= fig.add_axes(rect1)
ax2.scatter(q,z, s=200, color = colors)

I wish those who downvoted my question would say why, there was hours of searching and trying to find this.

Anyway here is the final image:

这篇关于Matplotlib 颜色图,散点图传递第三个颜色变量:RGBA 参数无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆