Issue
I have three column data file. First and second columns are x and y axes, respectively. I would like to give color to the plot in the form of a matrix as shown in an example figure (with different shades of grey).
I tried the following code, but is not reading the values of column z properly.
import numpy as np
import matplotlib.pyplot as plt
db=np.loadtxt('text.txt')
x=db[:,0]
y=db[:,1]
z=db[:,2]
colors = ['#5BFF00','#99CCFF','#FF5700']
for i in z:
if i < 9:
colors.append(1)
if 9 < i < 25:
colors.append(2)
else:
colors.append(3)
plt.scatter(x, y, c=colors)
plt.show()
A part of my datafile
1 2 5.02
1 3 18.011
1 4 0.31
1 5 24.14
Solution
You're appending to the colors
list that, I assume, contains the three different colours that you are wanting on the plot. Instead have a new list to contain the colours to be plotted, e.g.,:
colors = ['#5BFF00','#99CCFF','#FF5700']
c = [] # colours to use in the plot
for i in z:
if i < 9:
c.append(colors[0])
if 9 < i < 25:
c.append(colors[1])
else:
c.append(colors[1])
plt.scatter(x, y, c=c)
This will not have the matrix form that you want, for which you should try a seaborn heatmap
(you can do it purely with Matplotlib), but the Seaborn interface is simpler. An example using the Seaborn heatmap (and the digitize
function from @mozway's answer) is:
import seaborn as sns
import numpy as np
data = np.loadtxt("test.txt")
nrows = data[:, 0].astype(int).max()
ncols = data[:, 1].astype(int).max()
darray = data[:, 2].reshape((nrows, ncols))
bins = [0, 9, 25, np.inf]
darray = np.digitize(darray, bins)
colours = ['#5BFF00','#99CCFF','#FF5700']
ax = sns.heatmap(darray, cmap=colours, cbar=False)
where I have used a test.txt
file containing:
1 1 0.3
1 2 5.02
1 3 18.011
1 4 0.31
1 5 24.14
2 1 0.5
2 2 10.1
2 3 5.4
2 4 28.9
2 5 9.1
3 1 0.5
3 2 32.4
3 3 4.3
3 4 12.7
3 5 0.45
4 1 90.4
4 2 20.5
4 3 7.6
4 4 15.8
4 5 21.4
5 1 0.53
5 2 3.4
5 3 15.9
5 4 21.3
5 5 100.3
which gives:
Answered By - Matt Pitkin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.