Matplotlib在给定CSV数据的情况下创建表面图(x,y,z,颜色)-获取错误的颜色 [英] Matplotlib create surface plot (x,y,z,color) given csv data - getting wrong colors

查看:141
本文介绍了Matplotlib在给定CSV数据的情况下创建表面图(x,y,z,颜色)-获取错误的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何读入四列数据以创建由第四个变量着色的表面图?就我而言,数据是使用四个嵌套的for循环生成的,因此最右边的列更改频率最高,而最左边的列更改频率最低。

How can I read in four columns of data to create a surface plot which is colored by the fourth variable? In my case, the data was generated using four nested for loops, so the rightmost columns change most frequently while the leftmost columns change least frequently.

到目前为止尝试过。

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import pylab
from scipy.interpolate import griddata

dat = open('ex.csv', 'w')
dat.write('x,y,z,c\n')
for x in range(20):
    for y in range(20):
             dat.write(','.join([str(s) for s in [x,y,x+y,x+y,'\n']]))
dat.close()

fig = matplotlib.pyplot.gcf()
subdat = np.genfromtxt('ex.csv', delimiter=',',skiprows=1)
X = subdat[:,0]
Y = subdat[:,1]
Z = subdat[:,2]
C = subdat[:,3]

xi = np.linspace(X.min(),X.max(),100)
yi = np.linspace(Y.min(),Y.max(),100)

zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')
ci = griddata((X, Y), C, (xi[None,:], yi[:,None]), method='cubic')

ax1 = fig.add_subplot(111, projection='3d')

xig, yig = np.meshgrid(xi, yi)
surf = ax1.plot_surface(xig, yig, zi,facecolors=cm.rainbow(ci))

m = cm.ScalarMappable(cmap=cm.rainbow)
m.set_array(ci)
col = plt.colorbar(m)
plt.show()


(着色是错误的,应该与具有连续渐变的高程值相同)

(coloring is wrong, should be the same as elevation value with continuous gradient)

推荐答案

这里的问题是 facecolors 未能正常化。尝试执行此操作,以明确地进行规范化:

The problem here is that the facecolors aren't normalizing as might be expected. Try this, which does the normalizing explicitely:

norm = matplotlib.colors.Normalize()
surf = ax1.plot_surface(xig, yig, zi, facecolors=cm.rainbow(norm(ci)))

< a href = https://i.stack.imgur.com/yBD3q.png rel = nofollow noreferrer>

这篇关于Matplotlib在给定CSV数据的情况下创建表面图(x,y,z,颜色)-获取错误的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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