Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

python - create heatmap2d from txt file

I have set of 2d data (30K) as txt file.

  X       Y
2.50    135.89
2.50    135.06
2.50    110.85
2.50    140.92
2.50    157.53
2.50    114.61
2.50    119.53
2.50    154.14
2.50    136.48
2.51    176.85
2.51    147.19
2.51    115.59
2.51    144.57
2.51    148.34
2.51    136.73
2.51    118.89
2.51    145.73
2.51    131.43
2.51    118.17
2.51    149.68
2.51    132.33

I plotted as a scatter plot with gnuplot but I would like to represent as a heatmap2d or density distribution. I looked through the examples in MatPlotLib or R and they all seem to already start with random data to generate the image.

I tried those code and get error like this

hist, edges = histogramdd([x,y], bins, range, normed, weights)

AttributeError: The dimension of bins must be equal to the dimension of the sample x. Script terminated.

Is there any methods to open txt file and plot this data in gnuplot, matplotlib. my scatter plot look like this enter image description here

i want to show this picture as contour map or density map with color code bar. my x-axis at range of 2.5-3.5 and y axis at range of 110-180 i have 30k data points

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're willing to do everything in Python, you can compute the histogram and build a contour plot in one script :

import numpy as np
import matplotlib.pyplot as plt

# load the data
M = np.loadtxt('datafile.dat', skiprows=1)

# compute 2d histogram
bins_x = 100
bins_y = 100
H, xedges, yedges = np.histogram2d(M[:,0], M[:,1], [bins_x, bins_y])

# xedges and yedges are each length 101 -- here we average
# the left and right edges of each bin
X, Y = np.meshgrid((xedges[1:] + xedges[:-1]) / 2,
                   (yedges[1:] + yedges[:-1]) / 2)

# make the plot, using a "jet" colormap for colors
plt.contourf(X, Y, H, cmap='jet')

plt.show()  # or plt.savefig('contours.pdf')

I just made up some test data composed of 2 Gaussians and got this result :

contour plot from 2d histogram


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...