1

Using this piece of code i get the temperatures and date times then insert them into a matplotlib (plt) using numpy (np)

# get date times and the temperatures of a certain city, info pulled from request
raw_date_times = [item['dt_txt'] for item in s['list']]
temperature_kelvins = [item['main']['temp'] for item in s['list']]

# Apply calculation on each item to make celsius from kelvins
temperatures = [round(item - 273.15) for item in temperature_kelvins]

# Filter out today's date from list of dates into date_times
today = datetime.today().date()
date_times = []
for i in raw_date_times:
    date =  datetime.strptime(i, '%Y-%m-%d %H:%M:%S').date()
    if date == today:
        date_times.append(i)

# Convert the array with integers of temperatures to strings to make both of same dimension
for i in range(0, len(temperatures)): 
    temperatures[i] = str(temperatures[i]) 

# get len of date_times and convert it into an array (i.e 6 becomes [0,1,2,3,4,5])
date_times_len = len(date_times)
    n = []
for i in range(0,date_times_len):
n.append(i)
            print (n)

# Plot out map using values
x = np.array(n)
y = np.array([temperatures])
my_xticks = [date_times]
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()


# date_times example = ['2020-03-17 12:00:00', '2020-03-17 15:00:00', '2020-03-17 18:00:00', '2020-03-17 21:00:00']
# temperatures example (before string)= [29, 31, 30, 25, 23, 22, 20, 23, 30, 33, 31, 27, 24, 23, 21, 23, 31]

However i keep getting this error:

    for val in OrderedDict.fromkeys(data):
TypeError: unhashable type: 'numpy.ndarray'

I researched a bit and found that it means that something went wrong with the shape i think. Is it because they are strings? If so then could you suggest a way to convert my datetimes into integers?

Thank you!

Full traceback:

Traceback (most recent call last):
  File "class-test.py", line 77, in <module>
    weatherData('gurgaon')
  File "class-test.py", line 55, in weatherData
    plt.plot(x, y)
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2761, in plot
    return gca().plot(
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 1646, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 216, in __call__
    yield from self._plot_args(this, kwargs)
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 339, in _plot_args
    self.axes.yaxis.update_units(y)
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/axis.py", line 1516, in update_units
    default = self.converter.default_units(data, self)
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/category.py", line 107, in default_units
    axis.set_units(UnitData(data))
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/category.py", line 175, in __init__
    self.update(data)
  File "/Users/Ronnie/.local/share/virtualenvs/weather-d3bb5uZO/lib/python3.8/site-packages/matplotlib/category.py", line 210, in update
    for val in OrderedDict.fromkeys(data):
TypeError: unhashable type: 'numpy.ndarray'
(weather) bash-3.2$ 
2
  • can you add full traceback? Commented Mar 18, 2020 at 5:12
  • Tell us about x and y - shape and dtype (assuming they are ndarray). What happens if you skip the plt.xticks line? Or it you drop the brackets on [date_times] (why are you using the []?). Commented Mar 18, 2020 at 5:37

3 Answers 3

1

I think this replicates a portion of your plot:

In [347]: date_times = ['2020-03-17 12:00:00', '2020-03-17 15:00:00', '2020-03-17 18:00:00', '2020-03-17 21:00:00'] 
     ...: temperatures = [29, 31, 30, 25, 23, 22, 20, 23, 30, 33, 31, 27, 24, 23, 21, 23, 31]                        
In [348]: len(date_times)                                                                                            
Out[348]: 4
In [349]: len(temperatures)                                                                                          
Out[349]: 17
In [350]: x = np.arange(len(date_times))                                                                             
In [351]: y = np.array(temperatures[:4])    
In [359]: plt.xticks(x, date_times);                                                                                 
In [360]: plt.plot(x,y);  

My arange is a shorter and faster way on constructing x than your:

In [361]: n = [] 
     ...: for i in range(0,4): 
     ...:     n.append(i) 
     ...: np.array(n) 

Note that I use date_times, not [date_times]; the later adds an extra layer of list. I can't reproduce your error, but the unnecessary [] might be causing problems. The ticks and labels parameters to xticks should have the same length.

The error looks like it occurs while creating the axes (xticks). It's using an array (x?) as a dictionary key. The error occurs deep in the plt code, so it is hard to trace it back to your inputs. So it's easier to just examine the inputs (x,y,date_times), and make sure they look reasonable (expected data and matching lengths).

Same error here:

TypeError: unhashable type: 'numpy.ndarray' when trying to plot a DataFrame

though off hand I don't see what similar or different.

===

This plots ok:

In [364]: plt.plot(date_times,y);  

but this produces the error:

In [365]: plt.plot([date_times],y);  

(as with your xticks, this has the unnecessary brackets).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! btw for the for loop i used this: for i in range(0,date_times_len): is it okay?
You don't need the loop. Use np.arange(date_times_len) to get an array of [0,1,2...]. Or even np.array(range(date_times_len)).
1

Maybe this can help

#first import
from datetime import datetime

a = datetime.now()
#converting into int 
a = int(a.strftime('%Y-%m-%d %H:%M:%S'))  #using strtime to convert datetime into int

4 Comments

so according to you i have to do this: date_times = int(date_times.strftime('%Y-%m-%d %H:%M:%S')) print (date_times) ?? where would 'a' get its value?
@beepbeep-boop you should use date_times =datetime.now() instead of today = datetime.today().date().
yeah okay thanks, but wait, @Cb9867 , can we use strings to make graphs using matplot on the x axis and int on the y axis?
@beepbeep-boop or if you don't want the seconds and minutes in your program and want only the todays date then you should use what you are using today = datetime.today().date() but also need to chance this line as %Y-%m-%d '
0

yes you can use string to make graph but your matplot version should be >2.1 or 2.2

import matplotlib.pyplot as plt
x = ["ABCD", "EEEEE", "LLLL"]
y = [5,2,3]

plt.plot(x, y)

plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.