Reputation: 39
In the data set I am trying to make a bar graph on top 10 artists that have the highest number of songs in top 500 songs of all time. I have the result, however I am unable to visualize it. I need to make a bar graph of the output that I am getting from this code. Can someone tell what code should I add to make a bar graph of the output. I imported pandas, seaborn and matplot, just need help with the code.
counts = dict()
for artists in my_data['artist']:
counts[artists] = counts.get(artists, 0) + 1
def keyfunction(k):
return counts[k]
plt.figure(figsize = (10, 30))
plt.title("Greatest Artists of All Time")
data = dict()
for key in sorted(counts, key=keyfunction, reverse=True)[:10]:
print(key, counts[key])
Need to make a bar plot of the following output
Elton John 18
The Beatles 16
Elvis Presley 12
The Jimi Hendrix Experience 12
The Four Tops 10
Muddy Waters 8
Sam Cooke 8
The Clash 8
U2 8
The Isley Brothers 8
Upvotes: 3
Views: 86
Reputation: 4921
There is another way that I'd like to show. If you prefer Matplotlib go with the solution provided by @Burning Alcohol.
import pandas as pd
counts = {
"Elton John": 18,
"The Beatles": 16,
"Elvis Presley": 12,
"The Jimi Hendrix Experience": 12,
"The Four Tops": 10,
"Muddy Waters": 8,
"Sam Cooke": 8,
"The Clash": 8,
"U2": 8,
"The Isley Brothers": 8
}
Create a DataFrame from the dictionary.
df = pd.DataFrame.from_dict([counts])
The following gives a barplot with a legend outside the box.
axes = df.plot.bar()
axes.legend(bbox_to_anchor=(1,1))
Another way is to put the labels in the x-axis. We first transpose the DataFrame.
tdf = df.T.reset_index()
tdf.columns = ['Artist', 'Counts']
And finally the plot.
tdf.plot.bar(x='Artist', y='Counts')
Upvotes: 0
Reputation: 2977
You may do it like this,
import numpy as np
import matplotlib.pyplot as plt
# I assumed your counts is a dictionary
counts = {
"Elton John": 18,
"The Beatles": 16,
"Elvis Presley": 12,
"The Jimi Hendrix Experience": 12,
"The Four Tops": 10,
"Muddy Waters": 8,
"Sam Cooke": 8,
"The Clash": 8,
"U2": 8,
"The Isley Brothers": 8
}
y_pos = np.arange(len(counts))
# Create bars
plt.bar(y_pos, counts.values())
# Create names on the x-axis
plt.xticks(y_pos, counts.keys())
# Show graphic
plt.show()
Upvotes: 1