Generating a frequency heat map in Python MatPlotLib reading X and Y coordinates from a CSV file

I recently came across a similar question about how to create a heat frequency map in Python using the MatPlotLib module .

This post was very useful, and I could run individual scripts and create patterns for random test data that was inherently generated by code. However, it’s difficult for me to adapt the code to create a heat map for the data I'm working with. The data is in a comma-delimited format (.csv).

Currently, I have 3,788 pairs of average quality ratings stored in this CSV file. These average quality scores range from 0 to 5. I'm trying to create a heatmap that fills the data in increments of .5 along the x and y axis (0-4,99,15,999, 1-1,499, etc.).

I would like to import the first column of the .csv file (webqualityratings) as the x-values ​​of the heat map, and the second column of the .csv file (inkersonqualityratings) are the y values ​​of the heat map.

The code I tried to adapt, published by "ptomato" and edited by Mike Graham, is as follows:

import numpy as np   
import numpy.random   
import matplotlib.pyplot as plt  

# Generate some test data  
x = np.random.randn(8873)  
y = np.random.randn(8873)  

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)  
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]  
plt.clf()  
plt.imshow(heatmap, extent=extent)  
plt.show() 

If someone can help me adapt this code to read in the data from my .csv file as indicated, I would always be grateful!

+3
source share
2 answers

numpy csv , numpy.loadtxt(),

import numpy as np   
import matplotlib.pyplot as plt  

dat = np.loadtxt('mydata.csv')

x, y = dat[:,0], dat[:,1]

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)  
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]  
plt.clf()  
plt.imshow(heatmap, extent=extent)  
plt.show() 
+5

Python csv :

http://docs.python.org/library/csv.html

matplotlib, csv .

import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import csv

with open(yourInputFile, "rb") as mycsv:
    reader = csv.DictReader(mycsv, dialect='excel-tab')

    for row in reader:
        x = row['name of first column']
        y = row['name of second column']
        heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
        extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
        plt.clf()
        plt.imshow(heatmap, extent=extent)

plt.show()

, DictReader, . , . , , , 100 + .

csv , .

, , matplotlib, .

-1

All Articles