箭型图中箭头的不同颜色 [英] Different colours for arrows in quiver plot
问题描述
我正在绘制箭头图,并且我的代码使用如下外部文件:
将 numpy 导入为 np导入matplotlib.pyplot作为plt将Matplotlib导入为mpl从 pylab 导入 rcParams数据= np.loadtxt(r'data.dat')x = 数据[:,0]y =数据[:,1]u = 数据[:,2]v = 数据[:,3]plt.quiver(x,y,u,v,angles ='xy',scale_units ='xy',scale = 1,pivot ='mid',color ='g')
数据文件基本上看起来像:
1 1 0 00 1 1 00 1 1 01 1 0 1
有没有一种方法可以针对不同的箭头方向绘制不同的颜色?
Ps.:我的数据文件中有更多的箭头,在一个不太合乎逻辑的句子中,就像我使用的例子一样.
这可能有用:
plt.quiver(x,y,u,v,np.arctan2(v,u),angles ='xy',scale_units ='xy',scale = 1,枢轴='mid',颜色='g')
请注意, plt.quiver
的第五个参数是一种颜色.
UPD.如果要控制颜色,则必须使用
您还可以像我的第一个示例一样使用第五个参数(与 colors
相比,其工作方式略有不同),并更改默认的colormap来控制颜色.
plt.rcParams['image.cmap'] = '配对'plt.figure(figsize=(6, 6))plt.xlim(-2, 2)plt.ylim(-2,2)plt.quiver(x,y,u,v,np.arctan2(v,u),angles ='xy',scale_units ='xy',scale = 1,枢轴='mid')
您也可以创建自己的颜色图,例如参见此处.
I am plotting an arrow graph and my code uses an external file as follows:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from pylab import rcParams
data=np.loadtxt(r'data.dat')
x = data[:,0]
y = data[:,1]
u = data[:,2]
v = data[:,3]
plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1, pivot='mid',color='g')
The data file basically looks like :
1 1 0 0
0 1 1 0
0 1 1 0
1 1 0 1
Is there a way to plot this with different colours for the different arrow directions?
Ps.: I have got a lot more arrows in my data file in a not very logical sentence like the one I am using as example.
This probably do the trick:
plt.quiver(x, y, u, v, np.arctan2(v, u), angles='xy', scale_units='xy', scale=1, pivot='mid',color='g')
Note that the fifth's argument of plt.quiver
is a color.
UPD. If you want to control the colors, you have to use colormaps. Here are a couple of examples:
Use colormap with colors
parameter:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
%matplotlib inline
ph = np.linspace(0, 2*np.pi, 13)
x = np.cos(ph)
y = np.sin(ph)
u = np.cos(ph)
v = np.sin(ph)
colors = arctan2(u, v)
norm = Normalize()
norm.autoscale(colors)
# we need to normalize our colors array to match it colormap domain
# which is [0, 1]
colormap = cm.inferno
# pick your colormap here, refer to
# http://matplotlib.org/examples/color/colormaps_reference.html
# and
# http://matplotlib.org/users/colormaps.html
# for details
plt.figure(figsize=(6, 6))
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.quiver(x, y, u, v, color=colormap(norm(colors)), angles='xy',
scale_units='xy', scale=1, pivot='mid')
You can also stick with fifth argument like in my first example (which works in a bit different way comparing with colors
) and change default colormap to control the colors.
plt.rcParams['image.cmap'] = 'Paired'
plt.figure(figsize=(6, 6))
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.quiver(x, y, u, v, np.arctan2(v, u), angles='xy', scale_units='xy', scale=1, pivot='mid')
You can also create your own colormaps, see e.g. here.
这篇关于箭型图中箭头的不同颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!