0

I am reading a text file and from that text file I would like to generate a heat map with matplotlib. This is my code so far:

import matplotlib.pyplot as plt
import numpy as np
import math
from matplotlib import colors
file_object = open("tokillamockingbird.txt", "r", encoding="utf-8")
reading = file_object.read()
new_read = reading.strip()
someWord = ''
list_words = []
for letter in new_read:
if letter in ",!.?":
   list_words.append(letter)
lenListWords = len(list_words)
lengthOfPunctuation = math.sqrt(lenListWords)
# generate a scaled plot for this
data = np.random.rand(lengthOfPunctuation,lengthOfPunctuation)
fig, axes = plt.subplots()

Up to here, I am stuck and I want to use RGB method in matplotlib to specifiy each color for a 'box' that the scaled plot has.

When I run this it is giving me this picture:

Matplotlib output

Therefore, how do I add a specific color to a specific box? (if this is 4x4 there will be 16 boxes and I want to know how to put a color to each box)

jhoepken
  • 1,842
  • 3
  • 17
  • 24

1 Answers1

0

You are not using the proper command to generate a heatmap, but a 2D plot. If you would have a look at this post, you would see that it is quite straight forward to generate it. You use (among other things)

plt.imshow(heatmap)
plt.show()

instead of

plt.plot(x,y)
plt.show()

Alternatively, if you are not fixed on using Matplotlib, you can use Seaborn, which is another Python package for plotting. It's quite handy for such heatmap based graphics that involve correlations and statistical analysis.

Community
  • 1
  • 1
jhoepken
  • 1,842
  • 3
  • 17
  • 24