Reputation: 65
I want to plot a bar graph between Years (on X-axis) and Mean Sales per Year (on Y-axis) using Matplotlib.
The code is as under:
mean_per_year=[]
for x in sorted(np.unique(array_converted[...,0])):
mean_per_year.append([x, np.average(array_converted[np.where(array_converted[...,0]==x)][...,1])])
mean_per_year_array = np.array(mean_per_year)
mean_sales_array = np.delete(mean_per_year_array, 0, axis=1)
year_array = np.delete(mean_per_year_array, 1, axis=1)
year_array = year_array.astype('int64')
mean_sales_array = mean_sales_array.astype('int64')
plt.bar(year, mean_sales)
plt.show()
However, when I call the plt.bar(year, mean_sales)
the module gives error:
float() argument must be a string or a number, not 'NoneType'.
Essentially, the years and mean_sales are numpy arrays contaning integer type values. I also converted them to list, but to no avail. In list format, the years array is: [[2001], [2002], [2003], ... , [2020]]. And the same goes for mean_sales.
I am using only Numpy, Matplotlib (no Pandas allowed). Any help will be highly appreciated :)
Thanks in advance.
Upvotes: 0
Views: 255
Reputation: 65
I had figured out the answer myself.
The problem arose because I had nested list. So mean_sales[0] will be [2001], but we want 2001.
Instead of creating a list (mean_per_year), I created a dictionary.
In the mean_per_year dictionary, the keys were years and mean values per year were values. I then used that to create the chart I desired.
mean_per_year={}
for x in sorted(np.unique(array_converted[...,0])):
mean_per_year[x] = np.mean(array_converted[np.where(array_converted[...,0]==x)][...,1])
years = mean_per_year.keys()
mean_sales_per_year = []
for elem in mean_per_year.values():
mean_sales_per_year.append(elem)
year_labels = ['2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']
plt.figure(figsize=(20, 10))
plt.bar(years_list, mean_sales_per_year, tick_label = year_labels, width = 0.8)
plt.xlabel('Years')
plt.ylabel('Mean Price')
plt.title('Mean Price per Year')
plt.show()
Upvotes: 1